Home >> Latest Articles >> How To Use Multiple Database In CodeIgniter

How To Use Multiple Database In CodeIgniter

CodeIgniter provides facility - How To Use Multiple Database In CodeIgniter. To Use Multiple Database In CodeIgniter, you have to create multiple Configurations Arrays in the database.php file. Connecting to Multiple Databases in the same CodeIgniter framework is easy.
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
);
You may also like - CodeIgniter Interview Questions and Answers
Connection to new database

By default the CodeIgniter connection statement is

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

//Default database query
$query = $this->db->select('name, email')->from('user')->where('id', 1)->get();


//Another database query
$query = $db2->select('name, email')->from('user')->where('id', 1)->get();

You may also like - Top 50 Laravel Interview Questions and Answers
Full Stack Tutorials

Author @FullStackTutorials | View all Articles