Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Multiple Databases Within CodeIgniter

DISCLAIMER: I'm new to web development

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 applicaton/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)?

Thank you so much for all of your help!

like image 720
imlouisrussell Avatar asked Sep 29 '11 17:09

imlouisrussell


1 Answers

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');
like image 179
Dalen Avatar answered Sep 21 '22 19:09

Dalen