简体   繁体   中英

Test database connection in php without username & password

There are some nice php database connection tests around, but they all seem to require a username & password. How would one confirm (using php and presumably mysqli) that a database server is up and would accept connections should one be attempted with a correct username & password, but report some details on the failure if the server was down or timed out or what not.

I would use the code 1045 to see if you can connect. This error code indicates that the credentials are incorrect. If the server responds with that code then it means it is reachable.

<?php

$reachable = false;

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
    $mysqli = new mysqli('localhost', 'some invalid user', 'wrong password');
} catch (mysqli_sql_exception $e) {
    if (1045 === $e->getCode()) {
        $reachable = true;
    }
}

var_dump($reachable);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM