数据库切换

时间:2014-07-08 04:23:22

标签: php mysql database replication

我正在使用mysql我想使用数据库,例如位于服务器A中,如果我的连接从服务器A丢失,它应该自动切换到我的localhost数据库,当它再次连接时应该切换到服务器甲

1 个答案:

答案 0 :(得分:1)

如果您只使用mysqli扩展,则应首先使用此代码尝试建立与服务器A的连接,如果它无法回退到服务器B,则每次加载页面时都会检查与服务器的连接。

<?php
$con = mysqli_init();
// set a timeout here, the time is in seconds, and this will affect both connections attempts (or more if you want).
$con->options(MYSQLI_OPT_CONNECT_TIMEOUT, 2);    
if(!$con->real_connect("serverA.localdomain:3306","root","password","dbname"))
{
  /* server A not connected */      
  if(!$con->real_connect("serverB.localdomain:3306","root","password","dbname"))
  {
    die('Cannot connect to server A or B');
  } 
  else
  {
    echo 'Connection established to server B';
  }
}
else
{
  echo 'Connection established to server A';      
}

// do your stuff here using $con->...   

$con->close();
?>