0

这是 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。

4

2 回答 2

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);

?>

于 2013-09-03T05:17:08.830 回答
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 表示您的服务器连接正常。

于 2013-09-03T05:13:50.933 回答