Connecting to Multiple Databases in CodeIgniter

codeigniter

You can connect to more than one database simultaneously in CodeIgniter.

In the database.php (inside application/config folder) file, you will find the following default database connection code.

$active_group = ‘default’;
$active_record = TRUE;

$db['default']['hostname'] = ‘localhost’;
$db['default']['username'] = ”;
$db['default']['password'] = ”;
$db['default']['database'] = ”;
$db['default']['dbdriver'] = ‘mysql’;
$db['default']['dbprefix'] = ”;
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = ”;
$db['default']['char_set'] = ‘utf8′;
$db['default']['dbcollat'] = ‘utf8_general_ci’;
$db['default']['swap_pre'] = ”;
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

Step 1: To connect to multiple databases at a time, copy the default record set and paste below the above code and change the multi-dimensional array key value ‘default’ to ‘new_conn’ (Key value can be anything).

Your new database connection record set will look like

$db['new_conn']['hostname'] = ‘localhost’;
$db['new_conn']['username'] = ”;
$db['new_conn']['password'] = ”;
$db['new_conn']['database'] = ”;
$db['new_conn']['dbdriver'] = ‘mysql’;
$db['new_conn']['dbprefix'] = ”;
$db['new_conn']['pconnect'] = TRUE;
$db['new_conn']['db_debug'] = TRUE;
$db['new_conn']['cache_on'] = FALSE;
$db['new_conn']['cachedir'] = ”;
$db['new_conn']['char_set'] = ‘utf8′;
$db['new_conn']['dbcollat'] = ‘utf8_general_ci’;
$db['new_conn']['swap_pre'] = ”;
$db['new_conn']['autoinit'] = TRUE;
$db['new_conn']['stricton'] = FALSE;

Step 2: Change the ‘pconnect’ value of all record sets to FALSE. This will make the “default” group as default connection. Other connections you will have to make manually. To connect to the other database, check step 3.

Step 3: To connect to another database, you need to specify the group name as follows:

$db2 = $this->load->database(‘new_conn’, TRUE);

And you are done.

To run a query, query statements should be like,
$db2->select(*);
$query = $db2->get(“users”);

You can connect to as many databases you want.

Have something to Add?

Loading Facebook Comments ...
Loading Disqus Comments ...