In this tutorial, We will learn how to connect multiple databases in CodeIgniter 3. it's easy to configure multiple database connections in CodeIgniter. you can simply add database query, join, etc with multiple databases.


Suppose, we have two databases:

  1. test_db1
  2. test_db2

Follow some steps:


Step 1: 

Add Database Configuration for both databases application/config/database.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');


$active_group = 'default';
$query_builder = TRUE;


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


$db['another_db'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => 'root',
	'database' => 'test_db2',
	'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
);


Step 2: 

Add Route application/config/routes.php

<?php

$route['test_db'] = 'welcome/test_db';


Step 4: 

Add Controller Method application/controllers/Welcome.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');


class Welcome extends CI_Controller {


	public function test_db()
	{
		$this->load->database();
		$query = $this->db->get("items");
		echo "<pre>";
		print_r($query->result());


		$second_DB = $this->load->database('another_db', TRUE); 
		$query2 = $second_DB->get("items");
		print_r($query2->result());
		exit;
	}
}


Finally, You need to run your application.