Codeigniter is the best way to use two different databases

Does anyone know how best to use 2 different databases in my application?

I need to store data in both databases, which are located in different ways (host, username, password, everything changes).

I plan to create models, as usual, and set the host, name, pass, etc. in the design.

+7
source share
4 answers

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

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

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

now you can create another group, let's 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 click

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

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

alternatively (as suggested in the sbaaaang comments), you can do $this->db=$DB2; so that everything is the same

and you can expand it to several groups, such as

  $DB1 = $this->load->database('group1', TRUE); $DB2 = $this->load->database('group2', TRUE); ... $DBn = $this->load->database('groupn', TRUE); 
+16
source

Well, I would just like to write my solution here, because I used less code, I think:

in database.php, I set the database groups like this for ex:

 $database['default']['dbname'] = 'db1'; $database['second_db']['dbname'] = 'db2'; 

then in models, I used the constructor to switch to the database, which I want to use as follows:

 //use db1 function __construct() { // Call the Model constructor parent::__construct(); $this->load->database('default',true); } //use db2 function __construct() { // Call the Model constructor parent::__construct(); $this->load->database('second_db',true); } 

If someone wants to show more solutions, please do it! These are just my two cents.

+4
source

I read that

 $db['default']['pconnect'] = FALSE; 

must be false for these things to work. Please correct me if I am wrong. For ALL of the multiple databases that you use, it should be turned off. I do not know if this is a good solution.

+4
source

Tried this and it works:

 $db['otherdb'] = array_merge($db['primarydb'], array( 'database' => 'otherdbname' )); 
0
source

All Articles