How To Use Multiple Database In CodeIgniter

Home >> Blog >> How To Use Multiple Database In CodeIgniter
By Admin Dec 21, 2019

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 (Load 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();

Close the Connections

//Close Default database Connection
 $this->db->close(); 


//Close Another database Connection
 $this->another_db->close();

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