Connecting multiple database in codeigniter

codeigniter

If you are using codeigniter for your application and compulsion to member going on complex database, In codeigniter using combined database is quite easy, You can easily association 2 or more database and fetch data from complex database table. Sometime it requires to be neighboring to along amongst merged database and codeigniter makes it understandable.

How to connect multiple database in codeigniter

First pretension in the application/config/database.php file regarding the subject of any text editor and specify the settings of the other database.
Following is the your default database configuration.

//Default database
$db['default'] = array(
    'dsn'       => '',
    'hostname' => 'localhost',
    'username' => 'dbusername',
    'password' => 'dbpassword',
    'database' => 'dbname',
    '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
);

Now using above parameter create choice database configuration

//New Database 
$db['db2'] = array(
    'dsn'       => '',
    'hostname' => 'localhost',
    'username' => 'dbusername',
    'password' => 'dbpassword',
    'database' => 'dbname',
    '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
);

After creating vibrant database configuration you dependence to load database simultaneously as per your application need. you can switch database any time any where as you nonexistence.

Loading another database

$db2 = $this->load->database('db2', TRUE);

Where the TRUE parameter tells CI that youd considering to recompense the database direct.

Now subsequent to example you can see how to call option database db2 at anytime anywhere to other changeable that you can use in your model..

function getCompanyDetails()
{
  $db2 = $this->load->database('db2', TRUE);
  $query = $db2->select('company_name, address')->get('companies');
  var_dump($query);
}

You can use above method to secure multiple database in codeigniter and fetch details from one or more database tables.

Leave a Reply