开发者

Connect to failover db in PHP

In php is there a quick way to say if db1 is unavailable connect to db2 instead?

开发者_开发知识库

Here is what I'm doing now:

$username="XXXXXXXXX";
$password="XXXXXXXXX";
$database="XXXXXXXXX";
$hostname="XXXXXXXXX";

mysql_connect($hostname,$username,$password);

@mysql_select_db($database) or die("unable to select database");


mysql_select_db will return a boolean indicating if it succeeded. http://id2.php.net/manual/en/function.mysql-select-db.php

So you'd rather write:
if (!($db = mysql_select_db($database))) {
 $db = mysql_select_db($database2);
}


mysql_connecet returns false if the connection fails.

$username="XXXXXXXXX";
$password="XXXXXXXXX";
$database="XXXXXXXXX";
$hostname="XXXXXXXXX";
$hostname2="XXXXXXXXX"; // let's assume they have the same username and pw

$conn=mysql_connect($hostname,$username,$password); //Connect to the database.


if (!$conn) {
  mysql_close($conn); 
  echo "Cannot connect to DB1"; 
  $conn=mysql_connect($hostname2,$username,$password); //Connect to the database.
  if (!$conn) {
    mysql_close($conn); 
    echo "Cannot connect to DB2"; 
    die('No DBs');
  }
}
else {
   // $conn has your connection
}

similar behavior with mysql_select_db (it returns false if it fails)


Sure.... I find this right after posting the question: http://www.evolt.org/failover-database-connection-with-php-mysql

I ended up doing this:

$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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜