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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog