Mysql多个数据库连接不起作用

时间:2017-06-27 16:02:00

标签: php mysql

我只是尝试连接像这个例子的二级数据库,但我不知道为什么拒绝工作。有什么想法吗?

我提到每个数据库连接都能正常运行。

$db_HOST = "localhost";
$db_USER = "db_user";
$db_PASS = "db_pass";
$db_NAME1 = "db_test1";
$db_NAME2= "db_test2";

$db_LINK1 = mysql_connect($db_HOST, $db_USER, $db_PASS) or die("Technical revision. Please try again later!");
mysql_select_db($db_NAME1, $db_LINK1) or die("Couldn't select database");

$db_LINK2 = mysql_connect($db_HOST, $db_USER, $db_PASS, true) or die("Technical revision. Please try again later!");
mysql_select_db($db_NAME2, $db_LINK2) or die("Couldn't select database");

我在日志文件中遇到的错误:

PHP Warning:  mysql_fetch_array() expects parameter 1 to be resource, boolean given in /config/global/variables.php on line 27

PHP Warning:  mysql_fetch_array() expects parameter 1 to be resource, boolean given in config/global/hello.php on line 3

谢谢!

3 个答案:

答案 0 :(得分:0)

您应该使用PDO,但如果您在数据库选择中使用链接,则代码可以正常工作。例如:

$db1 = mysql_connect($hostname, $username, $password); 
$db2 = mysql_connect($hostname, $username, $password, true); 

mysql_select_db('database1', $db1);
mysql_select_db('database2', $db2);

应该有用。您忘记选择应在每个链接上使用哪个数据库。

答案 1 :(得分:0)

执行以下操作(使用 PDO 而不是mysql_connect,因为后者已弃用):

$db_HOST = "localhost";
$db_USER = "db_user";
$db_PASS = "db_pass";
$db_NAME1 = "db_test1";
$db_NAME2= "db_test2";

try {
    $db_LINK1 = new PDO('mysql:host='.$db_HOST.';dbname='.$db_NAME1, $db_USER, $db_PASS);
    foreach($db_LINK1->query('SELECT * from FOO') as $row) {
        print_r($row);
    }
    $dbh = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

try {
    $db_LINK2 = new PDO('mysql:host='.$db_HOST.';dbname='.$db_NAME2, $db_USER, $db_PASS);
    foreach($db_LINK2->query('SELECT * from FOO') as $row) {
        print_r($row);
    }
    $dbh = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

更多信息:php.net/manual/en/pdo.connections.php

如果第二次连接失败,请检查确切的错误消息。

答案 2 :(得分:0)

我知道我发现了这个问题。 我忘了更改所有与新的多重连接的查询。 LE:Solve确认了!谢谢大家!