user387049
user387049

Reputation: 6857

PHP Database Class and new() Function

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

Upvotes: 0

Views: 174

Answers (3)

Wrikken
Wrikken

Reputation: 70490

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.
    }

}

Upvotes: 0

Pekka
Pekka

Reputation: 449475

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.

Upvotes: 2

NikiC
NikiC

Reputation: 101936

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

Upvotes: 5

Related Questions