使用php用户定义函数的多个数据库连接

时间:2013-09-03 04:59:07

标签: php mysql php-5.3 mysql-5.5

这是config.php的代码我将这个文件包含在所有php文件中:

<?php
$db_name = 'localhost';
$db_user = 'XXXXXX';
$db_pass = 'XXXXXXXXXX';
function db_connect1()
{
    global $db_name, $db_user, $db_pass;
    $conn = mysql_connect($db_name, $db_user, $db_pass);
    mysql_select_db('test1', $conn) or die('Could not select database.');
    return $conn;
}
db_connect1();
?>

这里我需要连接另一个数据库test2。

2 个答案:

答案 0 :(得分:1)

您可以多次调用mysql_connect(),但如果参数相同,则需要为另一个连接传递true

<?php
$db_name = 'localhost';
$db_user = 'XXXXXX';
$db_pass = 'XXXXXXXXXX';
function db_connect1()
{
    global $db_name, $db_user, $db_pass;
    $conn1 = mysql_connect($db_name, $db_user, $db_pass);
    $conn2 = mysql_connect($db_name, $db_user, $db_pass,true);
    mysql_select_db('test1', $conn1) or die('Could not select database test1.');
    mysql_select_db('test2', $conn2) or die('Could not select database test2.');

    $conn = new stdClass();
    $conn->conn1 = $conn1;
    $conn->conn2 = $conn2;

    return $conn;
}
$conn = db_connect1();

然后查询数据库test1,执行以下操作:

mysql_query('select * from tablename', $conn->conn1);

和数据库test2:

mysql_query('select * from tablename', $conn->conn2);

&GT;

答案 1 :(得分:0)

试试这个

$db_name = 'localhost';
$db_user = 'XXXXXX';
$db_pass = 'XXXXXXXXXX';
function db_connect1($dbname) {
   global $db_name, $db_user, $db_pass;
   $conn = mysql_connect($db_name, $db_user, $db_pass);
   if($conn) {
      mysql_select_db($dbname, $conn) or die('Could not select database.');
      return $conn;
   } else {
      die("Error occurred while connect to the server.");
   }
}

每次调用函数并设置参数时。

echo db_connect1('test1');
echo db_connect1('test2');

回显该函数,因为您正在使用return关键字并检查如果它返回1则表示您的服务器连接正常。