Mysql Backup Connection in PHP

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I notice with PHP if a connection cannot be established to a mysql
server with mysql_connect() PHP will timeout and never try the backup
server.  In this example:

$db = mysql_connect('', 'username', 'password');
if (!$db) {
   $db = mysql_connect('', 'username', 'password');

This works great and connects to the 2nd database if the 1st one
rejects the connection completely; however, if the 1st db is under high
load and doesn't respond for 10+ seconds it never jumps to the 2nd one.
 Curious if there's a better way to accomplish this.  If the 1st db
doesn't respond in 1 second max I'd like to hop to the 2nd one.

Does the newer mysqli_connect handle this better, anyone know?

Re: Mysql Backup Connection in PHP

Don't know about mysqli_connect() but you could use fsockopen() and set
a short timeout, close the connection and then reconnect with

I would hope there was a tidier solution that this though. Perhaps load
balancing on the backup server, in relation to how much it can handle?

Re: Mysql Backup Connection in PHP

Another issue I'm trying to overcome is locking issues.  We do
dual-master replication, and in the event a table is locked on db1, it
should still be readable on db2.  It would be great to have a way to
timeout a connection if no response rcv'd in say.. 2 seconds for it to
kick to the 2nd server.

Site Timeline