Skip to page content or skip to Accesskey List.
Search evolt.org
evolt.org login: or register

Work

Main Page Content

Failover Database Connection with PHP + mySQL

Rated 2.83 (Ratings: 4) (Add your rating)

Log in to add a comment
(7 comments so far)

Want more?

 
Picture of SJBDude7

Stephen Belue

Member info | Full bio

User since: February 18, 2007

Last login: March 03, 2007

Articles written: 1

Imagine, you're connecting to a mySQL database with PHP, but hell, you want a bit more robustness. So why would you want just one database? You'd use a failover right? So if the first database is down or just doesn't connect, it can connect to the next one. Here's how to do that (I'm assuming you're already replicating between databases so that they're roughly in sync).

Here's how you do it. Firstly, you'll have to define some things...

<?php
$host
=""; //Database host.
$user=""; //Database username.
$pass=""; //Database password.
$dbase=""; //Database.
$host2=""; //Database host two... This is optional: in case the other database cannot connect.
$user2=""; //Database username two... This is optional: in case the other database cannot connect.
$pass2=""; //Database password two... This is optional: in case the other database cannot connect.
$dbase2=""; //Database two... This is optional: in case the other database cannot connect.
?>

View the comments, they are simple yet... informative. Now, the one thing that can make all of this come true:

<?php
$connect
=mysql_connect($host,$user,$pass); //Connect to the database.
?>

That will connect to the mySQL database with the currently defined variables. So, obviously, if $connect does that, what would $connect2 do?

<?php
$connect2
=mysql_connect($host2,$user2,$pass2); //Connect to the database.
?>

It connects to the database! But, oh, it's the second one. Strange, isn't it? Now, you can check if the database connected or not by checking if its true, or false.

<?php
if (!$connect) {
  
mysql_close($connect); //Ends the current connection to the database.
  
echo "Cannot connect to the first database!"; //Display the text inside the quotes.
}
else {
  echo
"Connected to the first database!"; //Display the text inside the quotes.
}
?>

Of course, how does it connect to the second database? Simple!

<?php
if (!$connect) {
  
mysql_close($connect); //Ends the current connection to the database.
  
echo "Cannot connect to the first database!<br />"; //Display text inside the quotes.
  
if (!$connect2) {
    
mysql_close($connect2); //Ends the current connection to the second database.
    
echo "Cannot connect to second database!"; //Display text inside the quotes.
  
}
  else {
    echo
"Connected to the second database!"; //Display text inside the quotes.
  
}
}
else {
  echo
"Connected to the first database!<br />Did not connect to the second database!"; //Display text in quotes
}
?>

Now, that's all this really does. It has some mysql_error() stuff in it too, and checks if the url is connection.php?type=1 before executing the code. I basically combined all of that into one script, all you have to do is edit the variables, and do:

<?php
include "connection.php";
?>

Here's the full script:

<?php
/////////////////////////////////////////////////////////
//Name --- Connection.php                              //
/////////////////////////////////////////////////////////
//Description --- Connects to a mySQL database easily  //
/////////////////////////////////////////////////////////
//Author --- [SJB]Dude7                                //
/////////////////////////////////////////////////////////

$host=""; //Database host.
$user=""; //Database username.
$pass=""; //Database password.
$dbase=""; //Database.
$host2=""; //Database host two... This is optional: in case the other database cannot connect.
$user2=""; //Database username two... This is optional: in case the other database cannot connect.
$pass2=""; //Database password two... This is optional: in case the other database cannot connect.
$dbase2=""; //Database two... This is optional: in case the other database cannot connect.

$connect=mysql_connect($host,$user,$pass); //Connect to the database.

if ($_GET["type"]=="1") {
  if (!
$connect) {
    
mysql_close($connect); //End the connection to possibly prevent SQL injection or just for safety.
    
$connect2=mysql_connect($host2,$user2,$pass2); //Connect to the host.
    
if (!$connect2) {
      die(
"<b>ERROR:</b> " . mysql_error()); //Receive an error if it cannot connect.
      
mysql_close($connect2); //End the connection to possibly prevent SQL injection or just for safety.
    
}
    else {
      
$dbconnect2=mysql_select_db($dbase2, $connect2); //Select the database.
      
if (!$dbconnect2) {
        die(
"<b>ERROR:</b> " . mysql_error()); //Receive an error if it cannot connect.
        
mysql_close($connect2); //End the connection to possibly prevent SQL injection or just for safety.
      
}
    }
  }
  else {
    
$dbconnect=mysql_select_db($dbase, $connect); //Select the database.
    
if (!$dbconnect) {
      die(
"<b>ERROR:</b> " . mysql_error()); //Receive an error if it cannot connect.
      
mysql_close($connect); //End the connection to possibly prevent SQL injection or just for safety.
    
}
  }
}
else {
  echo
"<b>ERROR:</b> Invalid argument '" . $_GET["type"] . "'."; //If the connect.php?type doesn't equal one, it will display this error.
}
?>
I was born in Philly. I started to code. I read some books. Yeah.

Thanks, but..

Submitted by danielpunt on September 13, 2007 - 17:37.

.. I really don't get the $_GET['type'] thing, but apart from that it can be done with far less code :
<?php
// Connect with MySQL database
// by danielpunt;

// Login for both users
$db1['host'] = 'localhost';
$db1['user'] = 'user';
$db1['pass'] = 'pass';
$db1['dbName'] = 'database';

$db2['host'] = 'localhost';
$db2['user'] = 'user2';
$db2['pass'] = 'user2';
$db2['dbName'] = 'database';

$conn = @mysql_connect($db1['host'], $db1['user'], $db1['pass']);
if(
$conn != false) {
    
$db = @mysql_select_db($db1['dbName']);
} else {
    
$conn = @mysql_connect($db2['host'], $db2['user'], $db2['pass']);
    
$db = @mysql_select_db($db2['dbName']);
}

if(
$conn == false OR $db == false) {
    die(
"Couldn't connect. <br> #" . mysql_errno() . ' : ' . mysql_error());
} else {
    echo
'Whoo! Connected!';
}
?>

login or register to post comments

Switch instead of If

Submitted by Original Sin on September 24, 2007 - 13:32.

I often find that using switch() instead of if() produces cleaner and shorter code. It becomes particularly beneficial if you for instance were to add another 3 dbs to connect to.

See below for a code example using switch(). You can read more about it at php.net/switch.

<?php
$db1
['host'] = 'localhost';
$db1['user'] = 'user';
$db1['pass'] = 'pass';
$db1['dbName'] = 'database';

$db2['host'] = 'localhost';
$db2['user'] = 'user2';
$db2['pass'] = 'user2';
$db2['dbName'] = 'database';

switch (
true) {
    case @
mysql_select_db($db1['dbName'],mysql_connect($db1['host'],$db1['user'],$db1['pass'])): break;
    case @
mysql_select_db($db2['dbName'],mysql_connect($db2['host'],$db2['user'],$db2['pass'])): break;
    default: echo
'Unable to connect to the database. God save us all!'; exit();
}
?>

login or register to post comments

IF for the shortest code

Submitted by atherix on September 29, 2007 - 05:26.

A one-liner IF statement is the most efficent. Also, why echo() and exit() when you can just die()?
<?php
if (!mysql_select_db($db1['dbName'],mysql_connect($db1['host'],$db1['user'],$db1['pass'])) && !mysql_select_db($db2['dbName'],mysql_connect($db2['host'],$db2['user'],$db2['pass']))) die("Unable to connect");
?>

login or register to post comments

Syncing?

Submitted by jtnt on October 1, 2007 - 20:26.

I'd love to know your method for keeping these two databases in sync, since given the above code, this would have to happen in real time so that at any point db1 was an exact duplicate of db2.

login or register to post comments

I'd love to know your method

Submitted by jestep on September 24, 2008 - 17:38.

I'd love to know your method for keeping these two databases in sync, since given the above code, this would have to happen in real time so that at any point db1 was an exact duplicate of db2.
The easiest way would be to set the databases up with a master-master replication schema. This way any changes on the primary database get applied to the secondary database and if the primary goes down, any changes made to the secondary database get updated on the primary when it comes back online. Short of clustering, it's one of the best ways to maintain redundancy and data consistency across multiple db's.

login or register to post comments

hardware requirement?

Submitted by Sten85 on November 2, 2008 - 10:25.

And how such a function load CPU? If I have 3-5Gb MySQL base and main server get it's limit (CPU)? So how many recources I need.

login or register to post comments

Terrible Article

Submitted by majikman on November 4, 2008 - 23:59.

This article is a terrible suggestion. Clearly the author has never worked on a load balanced/redundant MySQL /PHP architecture before.

You cannot rely on the PHP script to manage connections because you have no way to persist the state of the database server. It is possible that the one connection might hiccup and not connect so it'll connect to db2 but the other one might remain to db1. If you have both processes writing to the same table, they'll clobber each other and you'll have data inconsistencies and your database will be trashed.

Using a Master-Master replication method doesn't work either because you have no guarantee that the bin logs on the db1 have been flushed to db2. There may be a hiccup in the replication so that you might have two separate processes writing to the same table on different database servers. The auto increment values will become inconsistent once replication catches up and you will have problems with your data again.

The only proper way to do this is to have all write activity hit one master database server and all read activity hits the other servers. If the master fails, then all write activity must be moved over to another database server. Traditionally, replication is done with master-slave. If you want a hot fail over, you need a master-master replication.

RTFM before you trash your database and especially before you preach something to the world that is completely wrong and shows up #1 on google.

login or register to post comments

The access keys for this page are: ALT (Control on a Mac) plus:

evolt.orgEvolt.org is an all-volunteer resource for web developers made up of a discussion list, a browser archive, and member-submitted articles. This article is the property of its author, please do not redistribute or use elsewhere without checking with the author.