Using Multiple Databases Within CodeIgniter
DI开发者_StackOverflow中文版SCLAIMER: 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!
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');
精彩评论