imlouisrussell
imlouisrussell

Reputation: 946

Using Multiple Databases Within CodeIgniter

SCENARIO: I'm building a web application that uses ion_auth to manage all of the user/administrator information (uses MySQL database), and each user has their own database (MySQL as well) for core application purposes. I've autoloaded the database that I'm using for ion_auth in the application/config/database.php file within CodeIgniter. I am using standard MVC format (individual models pertaining to each database).

ISSUE: I'm needing to know how to use multiple databases at once within CodeIgniter easily and efficiently. Do I need to link the two database schemas together, or will CodeIgniter do that for me? Are there any resources out there that address this issue (I've had trouble trying to find one)?

Upvotes: 12

Views: 8592

Answers (1)

Dalen
Dalen

Reputation: 8986

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');

Upvotes: 23

Related Questions