在PHP MySQL中切换数据库连接

时间:2013-10-14 06:38:15

标签: php mysql database

我使用PHP MySQL制作了一个Web应用程序。在开发之后,我需要添加允许存档年度数据的功能,这转换为我复制整个数据库的特殊解决方案。

问题是,我有一个标准的  connection.php'文件,包含在系统的所有php文件中,用于存储数据库服务器身份验证详细信息和名称。代码如下所示:

$hostname_db_ntu = "localhost";
$database_db_ntu = "ntu";
$username_db_ntu = "root";
$password_db_ntu = "";
$db_ntu = mysql_pconnect($hostname_db_ntu, $username_db_ntu, $password_db_ntu) or trigger_error(mysql_error(),E_USER_ERROR); 

那么,如何让我的系统动态切换数据库?我需要更改' $ database_db_ntu'变量值基本上。正在使用另一个php编辑php文件我唯一的选择吗?

(我知道mysql_ *已经折旧了,我尽可能地反驳了。)

编辑:澄清:

整个系统使用一个包含多个表的数据库,所有页面都使用此代码高于的包含文件与该数据库连接。

我需要一个解决方案,我可以在某处修改它 包含文件以反映所选数据库,并相应地创建连接。

4 个答案:

答案 0 :(得分:2)

如何使用if .. else语句:

if ($dbcon1) {
$hostname_db_ntu = "localhost";
$database_db_ntu = "ntu";
$username_db_ntu = "root";
$password_db_ntu = "";
$db_ntu = mysql_pconnect($hostname_db_ntu, $username_db_ntu, $password_db_ntu) or trigger_error(mysql_error(),E_USER_ERROR);
} else {

//database connection2 here
}

然后,您需要传递$ dbcon1的值来决定使用哪个连接。

答案 1 :(得分:1)

建立另一个数据库连接。这应该有用。

$db_ntu2 = mysql_pconnect($hostname_db_ntu2, $username_db_ntu2, $password_db_ntu2) or trigger_error(mysql_error(),E_USER_ERROR);

答案 2 :(得分:1)

      $hostname_db_ntu = "your host name";
       $database_db_ntu = "your database name";
       $username_db_ntu = "root or username you have set";
      $password_db_ntu = "";
     $db_ntu = mysql_connect($hostname_db_ntu, $username_db_ntu, $password_db_ntu) or    trigger_error(mysql_error(),E_USER_ERROR); 

   $db_connect = mysql_select_db(" $database_db_ntu" ,$db_ntu) or die("!db");

答案 3 :(得分:0)

所以,这就是我所做的。我根据用户想要使用的数据库版本设置会话变量。然后,我编辑了我的全局'connections.php'脚本,如下所示:

session_start();
$hostname_db_ntu = "localhost";
if(isset($_SESSION['version']))
$database_db_ntu = $_SESSION['version'];
else
$database_db_ntu = "ntu";
$username_db_ntu = "root";
$password_db_ntu = "";
$db_ntu = mysql_pconnect($hostname_db_ntu, $username_db_ntu, $password_db_ntu) or trigger_error(mysql_error(),E_USER_ERROR); 

这种方法的优点是,我可以允许用户切换数据库,而无需去编辑我使用数据库的每个php文件。