Connect to multiple databases in Codeigniter

You can do this by adding following code in database.php. It may be useful .

/* FIRSTDB */
$active_group = “firstdb”;
$active_record = TRUE;

$db[‘firstdb’][‘hostname’] = “your hostname”;
$db[‘firstdb’][‘username’] = “your username”;
$db[‘firstdb’][‘password’] = “your password”;
$db[‘firstdb’][‘database’] = “your database”;
$db[‘firstdb’][‘dbdriver’] = “mysql”;
$db[‘firstdb’][‘dbprefix’] = “”;
$db[‘firstdb’][‘pconnect’] = TRUE;
$db[‘firstdb’][‘db_debug’] = TRUE;
$db[‘firstdb’][‘cache_on’] = FALSE;
$db[‘firstdb’][‘cachedir’] = “”;
$db[‘firstdb’][‘char_set’] = “utf8”;
$db[‘firstdb’][‘dbcollat’] = “utf8_general_ci”;

/* SECONDDB */
$active_group = “seconddb”;
$active_record = TRUE;

$db[‘seconddb’][‘hostname’] = “your hostname”;
$db[‘seconddb’][‘username’] = “your username”;
$db[‘seconddb’][‘password’] = “your password”;
$db[‘seconddb’][‘database’] = “your database”;
$db[‘seconddb’][‘dbdriver’] = “mysql”;
$db[‘seconddb’][‘dbprefix’] = “”;
$db[‘seconddb’][‘pconnect’] = TRUE;
$db[‘seconddb’][‘db_debug’] = TRUE;
$db[‘seconddb’][‘cache_on’] = FALSE;
$db[‘seconddb’][‘cachedir’] = “”;
$db[‘seconddb’][‘char_set’] = “utf8”;
$db[‘seconddb’][‘dbcollat’] = “utf8_general_ci”;

And then add the below code in models to load a specific db:

function __construct()
{
// Call the Model constructor
parent::__construct();
$this->load->database(‘firstdb’,true);
}

function __construct()
{
// Call the Model constructor
parent::__construct();
$this->load->database(‘seconddb’,true);
}

Leave a Reply

Your email address will not be published. Required fields are marked *