coding, hacking, startups, computer security, technology and more

Load Balanced MySQL With Failover Using PHP

Simple MySQL database redundancy (with load balancing) can easily be obtained using PHP:

function connectDatabase($sDatabaseName) {
  $sUsername = 'myusername';
  $sPassword = 'mypassword';
  // database server hostnames
  $arrDBServers = array(

  // While we have available servers which we can connect to...
  while (count($arrServers)) {
    $sHostname = array_shift($arrDBServers);
    if ($resSQL= @mysql_connect($sHostname, $sUsername, $sPassword, true))

 if ($resSQL)
   if (mysql_select_db($sDatabaseName, $resSQL))
     return $resSQL;

 // if we get here, something is very wrong!
 // you should replace this line with your own error handling
 die( mysql_error() );

Once implemented, ensure you modify your php.ini accordingly to allow failover to happen in a timely manner in the event of a connection timeout..  In a default PHP installation the mysql_connect_timeout is set to 60 seconds, I changed this on my install to just 1 second. Don't forget to restart apache once you're done modifying php.ini !

I hope you will find this snippet useful when your web app starts to get busy!