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 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件
  • ¥15 K8S部署二进制集群过程中calico一直报错
  • ¥15 java python或者任何一种编程语言复刻一个网页
  • ¥20 如何通过代码传输视频到亚马逊平台
  • ¥15 php查询mysql数据库并显示至下拉列表中
  • ¥15 freertos下使用外部中断失效
  • ¥15 输入的char字符转为int类型,不是对应的ascall码,如何才能使之转换为对应ascall码?或者使输入的char字符可以正常与其他字符比较?
  • ¥15 devserver配置完 启动服务 无法访问static上的资源
  • ¥15 解决websocket跟c#客户端通信