What is the correct way of checking if the MySQL server is up and running before trying to retrieving data from it ?
I'm using PHP and MySQLI in the object orientated way.
I'm semi-new to MySQLI and managed to write something useful for my website. A voting system.
I have some code on my website that retrieves data from the MySQL server and displays it on the website.
This works fine as long at the MySQL server is up and running and are able to connect to it.
But if i turn off the MySQL server or otherwise my PHP code is not able to connect to the SQL server my website hangs for a while until timeout and then part of my website is not displayed.
According to the mysqli documentation,
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
I further suppose you could check the value of connect_errno to get a better idea of why the connection failed.
Most of web sites are not just "retrieve some data from the MySQL server and displays it", but have ALL the data stored in DB. So, a database server become a vital part of the site. With 2 consequences:
So, nobody actually do such a verifications you are asking for - they are working on making a DB server 100% available, not on a verification if it's up or down.
So you have to.
each time you can give call to this function and check is server is running or not
<?php
// Create connection
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>