Best thing is use Codeigniter provided database.php.
Important !!!!!
You no need to create separate database configurations if you only need to use a different database on the same connection. You can switch to a different database when you need to, like this:
$this->db->db_select($database2_name);
How to create Multiple database
In Codeigniter 2
Load first databse as defult
$db['default']['hostname'] = 'localhost';
$db['db_1']['username'] = 'root';
$db['db_1']['password'] = '';
$db['db_1']['database'] = 'my_db';
$db['db_1']['dbdriver'] = 'mysql';
$db['db_1']['dbprefix'] = '';
$db['db_1']['pconnect'] = TRUE;
$db['db_1']['db_debug'] = TRUE;
$db['db_1']['cache_on'] = FALSE;
$db['db_1']['cachedir'] = '';
$db['db_1']['char_set'] = 'utf8';
$db['db_1']['dbcollat'] = 'utf8_general_ci';
$db['db_1']['swap_pre'] = '';
$db['db_1']['autoinit'] = TRUE;
$db['db_1']['stricton'] = FALSE;
Load Second database
$db['db_2']['hostname'] = 'localhost';
$db['db_2']['username'] = 'root';
$db['db_2']['password'] = '';
$db['db_2']['database'] = 'my_db_2';
$db['db_2']['dbdriver'] = 'mysql';
$db['db_2']['dbprefix'] = '';
$db['db_2']['pconnect'] = TRUE;
$db['db_2']['db_debug'] = TRUE;
$db['db_2']['cache_on'] = FALSE;
$db['db_2']['cachedir'] = '';
$db['db_2']['char_set'] = 'utf8';
$db['db_2']['dbcollat'] = 'utf8_general_ci';
$db['db_2']['swap_pre'] = '';
$db['db_2']['autoinit'] = TRUE;
$db['db_2']['stricton'] = FALSE;
In Codeigniter 3
Load First database
$db['db_1'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
'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
Load Second database
$db['db_2'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
'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
How to load database?
In codeigniter 2
$db_1 = $this->load->database('db_1', TRUE); # load First DB
$db_2 = $this->load->database('db_2', TRUE); # load Second DB
$query = $secondDb->select('first')->get('login');
By setting the second parameter to TRUE (boolean) the function will return the database object.
How to use this in Query??
Early when single DB we use this(below) lines at end of the Query.
$this->db->query();
$this->db->result();
But now just little bit change to it
$db_1->query();
$db_1->result();
# or
$db_2->query();
$db_2->result();