在php中有一种快速的方法可以说db1是否不可用而是连接到db2?
以下是我现在正在做的事情:
$username="XXXXXXXXX";
$password="XXXXXXXXX";
$database="XXXXXXXXX";
$hostname="XXXXXXXXX";
mysql_connect($hostname,$username,$password);
@mysql_select_db($database) or die("unable to select database");
答案 0 :(得分:2)
mysql_select_db将返回一个布尔值,指示它是否成功。 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);
}
答案 1 :(得分:1)
如果连接失败,mysql_connecet将返回false。
$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
}
与mysql_select_db类似的行为(如果失败则返回false)
答案 2 :(得分:0)
当然......我在发布问题后发现了这一点:http://www.evolt.org/failover-database-connection-with-php-mysql
我最终这样做了:
$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();
}