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.
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
);
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.
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();
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.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
Thank u for make it easy
thanks a lot
Thanks u
its working …thanks you 😀
thanks a lot