开发者

PHP Database Class and new() Function

开发者 https://www.devze.com 2023-01-23 19:00 出处:网络
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

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
开发者_Python百科

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


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


You're not showing the full class, but the most probable reason is that you are not passing the current connection to the mysql_query() command.

Save $dbh as a property of your class, and add the connection parameter to each mysql_ function that accepts it:

mysql_query("SELECT * from.......", $this->dbh);

That said, if you are building this from scratch at the moment, take a look whether you don't want to use PDO instead. It is better, safer and more flexible than the old style mySQL library.


If you are using the mysql extension (using either mysqli or PDO_MySQL would give both superior performance, more features, etc., so check that for new code), you'll have to store the database handle, and use that on every mysql_* call:

class db {
....
    function query($query){
        return mysql_query($query, $this->dbh);//notice the second parameter.
    }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消