Codeigniter: What is the best practice to maintain multiple database connection datas? Codeigniter: What is the best practice to maintain multiple database connection datas? codeigniter codeigniter

Codeigniter: What is the best practice to maintain multiple database connection datas?


On your application/config/constants.php write:

define('ENVIRONMENT', 'development'); switch(ENVIRONMENT):case 'development': # DB defined('DB_HOST')      ? null : define('DB_HOST', 'localhost');defined('DB_USER')      ? null : define('DB_USER', 'root');defined('DB_PASSWORD')  ? null : define('DB_PASSWORD', '');defined('DB_NAME')      ? null : define('DB_NAME', 'dev_db');break; case 'production': # DB defined('DB_HOST')      ? null : define('DB_HOST', 'production');defined('DB_USER')      ? null : define('DB_USER', 'production_user');defined('DB_PASSWORD')  ? null : define('DB_PASSWORD', '12345');defined('DB_NAME')      ? null : define('DB_NAME', 'production_db');break; endswitch;

Then on your application/config/database.php

$db['default'] = array(    'hostname' => DB_HOST,    'username' => DB_USER,    'password' => DB_PASSWORD,    'database' => DB_NAME,);


I do not know if this is the best solution, however, it is the simplest to implement and always worked very well for me:

After the declaration of $db['default']:

$db['default'] = array(    'dsn'   => '',    'hostname' => 'localhost',    'username' => '...',    'password' => '...',    ...);

I add this code:

if (ENVIRONMENT == 'development'){    $db['default']['username'] = 'root';    $db['default']['password'] = 'XXXXX';    $db['default']['database'] = 'developmentdatabasename';}

In the index.php of your project:

define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');


if you use apache - activate SetEnvIf (if it itsn't already)

after that put in your htaccess

SetEnvIf Host localhost$ CI_ENV=developmentSetEnvIf Host testhost$ CI_ENV=testingSetEnvIf Host productionhost$ CI_ENV=production

now just simply create in your application/config/ folder 3 folder named development, testing and production

and if you put now your different config files in this folders - ci accesses it depending on your current working environment

please follow the CI Documentation for further Information