Link to home
Start Free TrialLog in
Avatar of bigjdve
bigjdve

asked on

How to connect to multiple database via mysqli?

Hello,

I have created a class when I used to connect to the database using the __construct function.  This class also act as my selecting and executing of query.  I get this working for connecting to one database as I define the database host, username, password and db_name as a constant.  Now I want to somehow be able to pass different database name to this class, how can I do this so that this class continue to work?  For example, my constant DB_NAME is "test database".  I want to contact to another database name "test2 database".  How can I make it work?

My code for my class:

**note the upper case name is define in another file**

class QueryBuilder
{
public $host = DB_HOST;
public $db_username = DB_USERNAME;
public $db_password = DB_PASSWORD;
public $db_name = DB_NAME;

public function __construct()
{
      $this->mysqli = new mysqli($this->host,$this->db_username,$this->db_password,$this->db_name);      
}

public function __destruct()
{
      $this->mysqli->close();
}

public function select($sql)
{
      $qry = $this->mysqli->query($sql);
}

public function query($sql)
{
      $qry = $this->mysqli->query($sql);
}

}
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Pass the credentials to the constructor as arguments, just like the select and query methods.
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bigjdve
bigjdve

ASKER

Ray_Paseur - the connection is working.  However, in my select or query method, I can not execute the query.

In my select method:

$qry = $this->mysqli->query($sql);

It does seem to recognize the "$this->mysqli".  I have this code for escaping the character
($this->mysqli->real_escape_string($value)) and it does not perform the escaping.

If I echo out the statement that build that sql statement, it does not understand.

For example:

echo $sql = "select * from table where id=".$this->mysqli->real_escape_string($value);

result: "select * from table where id="";

If I remove the escape string, it will properly echo with "select * from table where id=1".

Any ideas why??
I did not see any escape code in the example above.  Can you please post THE ACTUAL CODE that is causing the issue?
Avatar of bigjdve

ASKER

This solution does work.  There was a typo in my password.
Ha!  Glad you got it working, and thanks for the points, ~Ray