dongni8969 2012-03-09 16:18
浏览 43
已采纳

通过PHP类使用两个数据库连接? (PHP / MySQL)

I have created these two files:

class myDbClass {
        function dbConnect($db) {
            $dbhost = 'myhost';
            $dbuser = 'myuser';
            $dbpass = 'mypassword';
            $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');      
            mysql_select_db($db, $conn);

        $this->dbConnection = $conn; 
    }

function dbSelect($sql) {       

    // run the query
    if ($result = mysql_query($sql, $this->dbConnection)) { 
        echo 'got a result';
    } else {
        echo 'error';
    }


} // end of dbSelect function
} // end of class

and

    include "myclass.php";

    // create two new objects

$db1 = new mkaDB();
    $db2 = new mkaDB();

// First Database Connection
$dbname1 = 'myfirstdatabase';
$db1->dbConnect($dbname1);


// Second Database Connection
$dbname2 = 'myseconddatabase';
$db2->dbConnect($dbname2);

$sql1 = "select * from mytable";
$db1->dbSelect($sql1);

$sql2 = "select * from myothertable";
$db2->dbSelect($sql2);

What I am trying to accomplish is creating 2 database connections, each connection to a different schema. I then want to be able to call each schema via the $db1->dbSelect or $db2->dbSelect. However, when I run this I get the "error" message from the dbSelect function. If I block out all calls to the $db2 object, the $db1 object does work.

I thought I could use $this->dbConnection to keep things sorted out, but this does not appear to be working.

  • 写回答

3条回答 默认 最新

  • doukangbin9698 2012-03-09 16:24
    关注

    You need the 4th, "new_link" parameter (php mysql_connect):

    "If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters."

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

报告相同问题?

悬赏问题

  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM