Connecting multiple database in codeigniter

If you are using codeigniter for your application and need to connect multiple database, In codeigniter using multiple database is quite easy, You can easily connect 2 or more database and fetch data from multiple database table. Sometime it requires to connect with multiple database and codeigniter makes it easy.


How to connect multiple database in codeigniter

First open the application/config/database.php file on any text editor and specify the settings of the another database.
Following is the your default database configuration.

//Default database
$db['default'] = array(
    'dsn'       => '',
    'hostname' => 'localhost',
    'username' => 'dbusername',
    'password' => 'dbpassword',
    'database' => 'dbname',
    '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
);

Now using above parameter create another database configuration

//New Database 
$db['db2'] = array(
    'dsn'       => '',
    'hostname' => 'localhost',
    'username' => 'dbusername',
    'password' => 'dbpassword',
    'database' => 'dbname',
    '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
);

After creating successful database configuration you need to load database simultaneously as per your application need. you can switch database any time any where as you want.

Loading another database

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

Where the TRUE parameter tells CI that you’d like to return the database object.

Now following example you can see how to call another database db2 at anytime anywhere to another variable that you can use in your model..

function getCompanyDetails()
{
  $db2 = $this->load->database('db2', TRUE);
  $query = $db2->select('company_name, address')->get('companies');
  var_dump($query);
}

You can use above method to connect multiple database in codeigniter and fetch details from one or more database tables.