Mysql – Load-balance two MySQL dbs from one PHP page

load balancingMySQLPHP

This is a really dumb question, but here goes.

  1. I've got one web server, running a simple PHP app.
  2. I've got two MySQL servers, with one replicated database, which powers the PHP app. I'm using two MySQL databases to deal with demand.

How can I (and indeed, can I) get the PHP app to alternate which MySQL server it uses?

The PHP line where I connect to the database is currently this:

$con = mysql_connect('10.0.0.2:3306','name','password')
  or die('Could not connect to the server!');

Is there a way I can load-balance with 10.0.0.2 and my other server? Thanks.

Best Answer

One really simple way: You could just use a random number to select between two connection strings, something like the following (this is pseudo-code, I don't speak PHP):

  $ran = gen_random();    // assuming range from 0..1
  if (ran < 0.5) then 
     $con = database1; 
  else 
     $con = database2; 

Real load balancing would be possible as well of course, you would have to check to load of your DB servers and select the one with the lower load.