What is the best way to check, from PHP, if connection to a MySQL server will succeed? I’ve seen some solutions that first try to open a socket connection (with fsockopen) and connect to MySQL (via whatever extension you are using) only if the socket connection was successful. I’m not too sure about this since you have to make two connections every time, does that hammer the server too much?
My problem is that if my MySQL server locks-up or stops working for whatever reason the web page just stops working (it load for a long time and then usually comes back with a 504 gateway time-out error). I’d like to display a user friendly error message if MySQL is not available. This would also, hopefully, avoid MySQL being hammered even more if it is already struggling, as new clients won’t connect to it until the server comes back up.
I’m using MySQLi extension if that is relevant.
What your need is the
MYSQLI_OPT_CONNECT_TIMEOUTspecify in mysqli::optionsdetails