new mysqli(): how to intercept an 'unable to connect' error?

For PHP 5.2.9+

if ($mysqli->connect_error) {
    die('Connect Error, '. $mysqli->connect_errno . ': ' . $mysqli->connect_error);
}

You'll want to set the Report Mode to a strict level as well, just as jeroen suggests, but the code above is still useful for specifically detecting a connection error. The combination of those two approaches is what's recommended in the PHP manual.


You need to tell mysqli to throw exceptions:

mysqli_report(MYSQLI_REPORT_STRICT);

try {
     $connection = new mysqli('localhost', 'my_user', 'my_password', 'my_db') ;
} catch (Exception $e ) {
     echo "Service unavailable";
     echo "message: " . $e->message;   // not in live code obviously...
     exit;
}

Now you will catch the exception and you can take it from there.


Check $connection->connect_error value.

See the example here: http://www.php.net/manual/en/mysqli.construct.php

Tags:

Php

Mysqli