Mysql – Quickly establishing if a remote MySQL connection is valid using PHP

MySQLPHP

I have a hosted website (Namecheap Pro shared hosting) that connects to a remote MySQL database using a read-only user privilege. This remote DB is updated by a separate system. The website works great until the remote DB goes down (Which it does now and again – cannot be resolved), at which point my website also fails with a PHP MySQL DB connect error.

To resolve this problem, I intend to create a copy of the remote DB locally on the hosted website, and synchronise this copy every hour. And then, when the website is reverting to the local copy, a message will appear on the screen informing the user that they are seeing cached data.

So far so good, except that I'm trying to get the website to test the remote DB first and if that fails, then connect to the local copy, but I can't figure out how to do a simple and quick test to establish this; my code just bombs out on a MySQL connect error after a page time-out when trying the remote DB first.

Of course, creating a replicated slave DB updated instantly when the remote DB is updated, and then pointing the website always and only at the slave would be ideal, but there are technical problems preventing this right now.

Any ideas on how to test a remote MySQL DB connection quickly so that a fallback local (copy) DB can be connected without much disruption the the user experience?

Best Answer

Well, on the mysqli constructor page for the php manual you have several examples on how to deal with connection errors, depending on the PHP version. For example, on the first code snippet, change the die() to

if ($mysqli->connect_error) {
    //try connecting to the backup node
    $mysqli = new mysqli('backup_node_host', 'my_user', 'my_password', 'my_db');
    ...
}

However, doing everything programmatically has its disadvantages, and as you are on DBA.stackexchange, and not on stackoverflow, I could suggest an alternative setup:

 read-only      read/write 
application     application
     |              |
     |              |
 HA Proxy           |
     |\             |
     | \            |
     |  \           |
     |   \          |
     |    \         |
     |     \        |
     |      \       |
     |       \      |
     |        \     |
     |         \    |
     |          \   |
     |           \  |     
 read-only      read/write
MySQL slave    MySQL Master
     ^              |
     |              |
     ----------------
    MySQL asynchronous
       replication

Obviously, this may cost more than a couple of shared hosting but avoids manual intervention (imports, failover management) and there is better management and control or certain type of errors (network timouts, etc.).