dongzhimin2231 2010-11-04 18:10
浏览 18
已采纳

PHP数据库类和new()函数

I have, what I think/hope, is a very simple PHP question. I have made a class to create database connections and issue common queries. I am trying to open two different database connections by creating two objects from the same database class. My code is as follows:

//connect to DB
 $dbh = new DB('localhost', 'db1', 'user', 'pass');

 //check connection
 if(!$dbh->getStatus()) {
  echo($dbh->getErrorMsg());
  die;
 }//if

 //connect to DB 2
 $dbh2 = new DB('localhost', 'db2', 'user', 'pass');

 //check connection
 if(!$dbh2->getStatus()) {
  echo($dbh2->getErrorMsg());
  die;
 }//if

However, when I call a method for $dbh to query the database, it attempts to query with the credentials for $dbh2.

My DB constructor is below:

class DB {
  function __construct($host, $db, $user, $pass) { 
   $dbh = mysql_connect($host, $user, $pass);
   mysql_select_db($db, $dbh);

   if(!$dbh) {
    $this->status = false;
    $this->error_msg = 'Error connecting to database: '.mysql_error();
    return(false);
   }//if


   $this->dbh = $dbh;
   $this->resetStatusAndErrors();
   return($dbh);
  }//_construct
  • 写回答

3条回答 默认 最新

  • 普通网友 2010-11-04 18:14
    关注

    Simple solution: Use PDO instead. It does exactly what you want, probably has better syntax and implementation and abstracts the interface for DB access.

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

报告相同问题?

悬赏问题

  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画