doutangliang7769 2017-06-27 16:02
浏览 59
已采纳

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

I just tried to connect a secondary database like this example bellow but i don't know why refuse to work. Any idea?

I mention that each database connection works properly individualy.

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

Errors i get in the log file:

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

Thank you!

  • 写回答

3条回答 默认 最新

  • duanjiaoxi4928 2017-06-27 16:16
    关注

    Do the following (with PDO instead of mysql_connect as the latter is deprecated):

    $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();
    }
    

    More info here: php.net/manual/en/pdo.connections.php

    If the second connection fails check the exact error message.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?