如何实现两个数据库服务器?

时间:2013-05-06 04:34:25

标签: php mysql

我有两个数据库服务器。例如:

(1) Local Server:

$host = "localhost";
$user = "root";
$pass = "";
$db="edoctor_s";

(2) Remote server
$host = "****.****.net";
$user = "***_***";
$pass = "****";
$db="*****";

如果未找到远程服务器,则本地服务器将处于活动状态。我想将它们用在一个php配置文件中。

4 个答案:

答案 0 :(得分:0)

检查服务器是本地的还是实时的

if($_SERVER['HTTP_HOST']=='localhost' || $_SERVER['HTTP_HOST']=='127.0.0.1'){
//local datebase
}
else{
// live database
}

答案 1 :(得分:0)

使用if条件并与ip进行比较,如果它是本地的,而不是与localhost ip进行比较,如127.0.0.1::1,如果IPv6使用其他连接,例如

<?php
   if($_SERVER['REMOTE_ADDR'] == '127.0.0.1' || $_SERVER['REMOTE_ADDR'] == '::1') { 
      // ::1 If loopback address is IPv6
      //Connect Local
   } else {
      //Connect Server
   }
?>

答案 2 :(得分:0)

也许我没有正确理解你,但你可以按优先级顺序创建一个配置值数组,尝试建立数据库连接,然后在建立连接后跳出循环。例如(使用MySQLi):

$db_config = array(
    // Try this first.
    array(
        'host' => 'xxxxx.xxxxx.xxxx',
        'user' => 'xxxx_xxxx',
        'pass' => 'xxxxx',
        'db' => 'xxxxx_s'
    ),

    // Then this.
    array(
        'host' => 'localhost',
        'user' => 'root',
        'pass' => '',
        'db' => 'edoctor_s'
    )

    // ...
);

$connection = null;

foreach ( $db_config as $config ) {
    $connection = mysqli_connect( $config[ 'host' ], $config[ 'user' ], $config[ 'pass' ], $config[ 'db' ] );

    // No need to keep looping if we have a valid connection.
    if ( ! mysqli_connect_error() )
        break;
    else
        $connection = null;
}

答案 3 :(得分:-1)

试试以下代码

//check for localhost
if($con = mysql_connect($host_local, $user_local , $pass_local )){
    mysql_select_db($db_local);
}elseif($con = mysql_connect($host_remote, $user_remote , $pass_remote)){   //Remote connection
    mysql_select_db($db_remote);
}

虽然我没有使用它,但可能满足你的要求