Using Multiple Databases Within CodeIgniter Using Multiple Databases Within CodeIgniter codeigniter codeigniter

Using Multiple Databases Within CodeIgniter


in your database config file add as many configuration groups as the numbers of your databases:

$db['a']['hostname'] = 'localhost';$db['a']['username'] = 'user';$db['a']['password'] = 'pw';$db['a']['database'] = 'db1';...$db['b']['hostname'] = 'localhost';$db['b']['username'] = 'user';$db['b']['password'] = 'pw';$db['b']['database'] = 'db2';...//set the default db$active_group = 'a';

then on your model initialize a class variable:

private $db_b;

and, into the contructor, set it as follow

__construct(){   ...   $this->db_b = $this->load->database('b', TRUE); }

now you are able to use the database b as usual:

$this->db_b->query('YOUR QUERY');

and obviously the default one as follow:

$this->db->query('YOUR QUERY');