YouTube Icon

Code Playground.

How to Connect Multiple Database in CodeIgniter

CFG

How to Connect Multiple Database in CodeIgniter

Generally, one database is used for a single web application. But sometimes we need to use two or more database in a single site. If your application built with CodeIgniter framework, it’s very easy to use multiple databases.

CodeIgniter provides an easy way to connect and use multiple database on the same or different server. You only need some minimal configuration to connect to more than one database in CodeIgniter application. This tutorial shows how you can connect and use multiple databases in CodeIgniter.

Multiple Database Configuration

Open the application/config/database.php file and specify the settings of the another database.

//Default database configuration
$db['default'] = array(
    'dsn'       => '',
    'hostname' => 'localhost',
    'username' => 'db_username',
    'password' => 'db_password',
    'database' => 'db_name',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt'  => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

//Another database configuration
$db['another_db'] = array(
    'dsn'       => '',
    'hostname' => 'localhost',
    'username' => 'db_username',
    'password' => 'db_password',
    'database' => 'db_name2',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt'  => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

Connecting to Multiple Databases

To connect to the multiple databases simultaneously, load the databases as follows.

//Load another database
$DB2 = $this->load->database('another_db', TRUE);

Set the second parameter to TRUE to get the database object.

Use Multiple Database in CodeIgniter

Now you can access multiple database connections by the database object.

//Default database query
$this->db->select('first_name, last_name');
$this->db->from('users');
$this->db->where('id', 99);
$query = $this->db->get();


//Another database query
$DB2->select('image');
$DB2->from('cdn_images');
$DB2->where('id', 25);
$query = $DB2->get();

Conclusion

In our example script, we have shown how to connect and use two databases in CodeIgniter 3. Using the same method you can connect to multiple database and retrieve data from another database in single CodeIgniter application.




CFG