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

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.

Leave a Comment