How to Connect to Multiple Databases in CodeIgnitor

CodeIgnitor framework provides a way for web developers to work with multiple databases. With just a few lines of code, you can easily connect to multiple databases and read different data types.

In application\config\database.php add these 2 database settings:

//1st database
$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'database1',
	'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
);

2nd database

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => '192.168.1.3',
	'username' => 'user2',
	'password' => 'passpass',
	'database' => 'database2',
	'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
);

Query from 2nd database

$db = $this->load->database('seconddatabase', TRUE);
$query = $db->select('*')->from('article')->where($conditions)->order_by('id', 'DESC')->get();
$result = $query->result();

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close