Codeigniter - the best way to use two different databases

Does someone knows the best practice for using 2 different database in my application?

I need to store data in both databases which are differently located (host,username,password , all does change).

I'm planning to create models as usual, and in construct set the db host,name,pass etc.

I'm not sure if you call this "best" way, but a way, as described in the tutorial, is this,

in the database file, you have the default configuration, a part of which is:

$db['default']['hostname'] = "localhost";
$db['default']['username'] = "user";
$db['default']['password'] = "database";
$db['default']['database'] = "db1";

now you can create another group, say we call it group1 and we want it to have everything the same as the default database settings except for the name, so you can do

$db['group1']=$db['default'];
$db['group1']['database']="db2";

then, when you want to use the second database, just go

$DB2 = $this->load->database('group1', TRUE);

and then, instead of $this->db->foo() , you will do $DB2->foo()

alternatively (as suggested in comments by sbaaaang), you can do $this->db=$DB2; to keep everything the same

and you can extend this to multiple groups like this

$DB1 = $this->load->database('group1', TRUE);
 $DB2 = $this->load->database('group2', TRUE);
 ...
 $DBn = $this->load->database('groupn', TRUE);
我来评几句
登录后评论

已发表评论数()

相关站点

+订阅
热门文章