I have a code that do some connection to mysql server and performs some actions with results of the query. Like this:
$connection = mysqli_connect($hostname, $dbusername, $dbpassword);
if(!$connection) {
echo mysqli_connect_error();
echo "connection to server with sitemap failed";
// do another stuff
}
else {
$db_select = mysqli_select_db($connection, $dbname);
$sqlmap = "SELECT url FROM sitemap";
$resmap = mysqli_query($connection, $sqlmap);
$arraymap = array();
while ($rowmap = mysqli_fetch_array($resmap)){
$arraymap[] = $rowmap["url"];
}
}
Sometimes mysql server, that has an internal ip 192.168.254.1, is offline, and the script execution will stop with fatal error "No route to host". When i used php 5.6 version (and mysql_connect instead of mysqli_connect), i used and approach with
if (!$connection) {
// do stuff for situation when mysql server is offline
}
else
{
// do stuff for situation when mysql server is online
}
to let the script continue to execute and make some other actions in sutiation when mysql server is offline. But now, in php 7.2, it just dies with fatal error. Is there a way to handle the "offline case" in php 7.2 using the mysqli_connect()?
I tried to echo mysqli_connect_error(), but again, it just dies with fatal error…
2
Answers
You should turn on mysqli error throwing with
mysqli_report(MYSQLI_REPORT_ALL);
and than catch it:In PHP 7.2 you can use mysqli_connect_errno() function returns the last connection error. If the connection to the MySQL server fails it will check the error code
2002
meaning no route to the host so you can handle offline cases and other cases separately.Reference: Can’t connect to MySQL server