Search code examples
phpcodeignitercodeigniter-2

How to switch to different default database in CodeIgniter?


I have two different connection set in the database config file. Once I have connected to the one of the database if I connect to the second database still the connection is not changed. I am getting table not found error.

$this->load->database(); //connecting to default db
$this->db->query('SELECT * from user'); //user table in default db and no error

$this->load->database('second_db');//connecting to second db
$this->db->load('SELECT * from statistic'); //table exists in second db but getting error
//The same work if I comment the first two lines

Solution

  • I have made it work myself.

    $this->load->database(); //connecting to default db
    $this->db->query('SELECT * from user'); //user table in default db and no error
    
    $this->load->database('second_db',FALSE,TRUE);//connecting to second db
    $this->db->load('SELECT * from statistic'); //table exists in second db but getting error
    //The same work if I comment the first two lines
    

    The only change is when loading the second database need to pass two extra parameters. First one FALSE - Don't return connection object Second TRUE - Change the Active record to the loaded DB