How to connect to multiple database via

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Tuyet
    New Member
    • Aug 2010
    • 3

    #1

    How to connect to multiple database via

    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**

    Code:
    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);
    }
    
    }
    Last edited by Niheel; Sep 8 '10, 04:24 PM. Reason: added code tags around code
  • guillermobytes
    New Member
    • Jan 2010
    • 77

    #2
    the code you give doesn't look quite right, but I assume you gave just a blueprint. If I understand the question you want to use the DB_NAME constant value as the database name, but the constant is defined in another file: use a require_once:
    Code:
    require_once '/constants_file_name.php';
    if the problem is that you want to connect to two databases in the same script, then you are doing it wrong, you should not use constants for defining your QueryBuilder data members.
    you could create public static data members and modify the database name before instantiating your QueryBuilder:
    Code:
    QueryBuilder::$db_name = 'test2_database';
    $qB = new QueryBuilder();
    or you could pass those to the constructor as parameters, as it is done in mysqli constructor.
    Code:
    QueryBuilder( $host, $user, $pass, $dbname);
    for that you should change your constructor to :
    Code:
    public function __construct($host, $user, $pass, $dbname)
    {
        $this->host = $host;
        $this->user = $user;
        //...
        $this->mysqli = new mysqli($this->host,$this->db_username,$this->db_password,$this->db_name);
    }

    Comment

    Working...