Here's a nifty little class which will load balance across multiple replicated MySQL server instances, using persistent connections, automatically removing failed MySQL servers from the pool.
You would ONLY use this for queries, never inserts/updates/deletes, UNLESS you had a multi-master situation where updates to any database serverautomatically replicate to the other servers (I don't know whether that's possible with MySQL).
Using this class, you get a connection to a MySQL server like this:
$con = MySQLConnectionFactory::create();
Here is the class (you'll need to customize the $SERVERS array for your configuration -- note that you would probably use the same username, password and database for all of the servers, just changing the host name, but you're not forced to use the same ones):
<?php
class MySQLConnectionFactory {
static $SERVERS = array(
array(
'host' => 'myHost1',
'username' => 'myUsername1',
'password' => 'myPassword1',
'database' => 'myDatabase1'),
array(
'host' => 'myHost2',
'username' => 'myUsername1',
'password' => 'myPassword2',
'database' => 'myDatabase2')
);
public static function create() {
$cons = array();
for ($i = 0, $n = count(MySQLConnectionFactory::$SERVERS); $i < $n; $i++) {
$server = MySQLConnectionFactory::$SERVERS[$i];
$con = mysql_pconnect($server['host'], $server['username'], $server['password']);
if (!($con === false)) {
if (mysql_select_db($server['database'], $con) === false) {
echo('Could not select database: ' . mysql_error());
continue;
}
$cons[] = $con;
}
}
if (count($cons) == 0) {
throw new Exception
('Unable to connect to any database servers - last error: ' . mysql_error());
}
$serverIdx = rand(0, count($cons)-1);
$con = $cons[$serverIdx];
return $con;
}
}
?>