Online Snippets Library

Use multiple DB connections In CodeIgniter

We can use multiple database in one CodeIgniter application.Here is simple example where we use second database.

  1. First we add additional databases in our configuration file.Go to applications/config folder open the database.php file and add below code in database.php file.

    $db['mydb2']['hostname'] = 'localhost';
    $db['mydb2']['username'] = 'root';
    $db['mydb2']['password'] = '';
    $db['mydb2']['database'] = 'ci2';
    $db['mydb2']['dbdriver'] = 'mysql';
    $db['mydb2']['dbprefix'] = '';
    $db['mydb2']['pconnect'] = TRUE;
    $db['mydb2']['db_debug'] = TRUE;
    $db['mydb2']['cache_on'] = FALSE;
    $db['mydb2']['cachedir'] = '';
    $db['mydb2']['char_set'] = 'utf8';
    $db['mydb2']['dbcollat'] = 'utf8_general_ci';
    $db['mydb2']['swap_pre'] = '';
    $db['mydb2']['autoinit'] = TRUE;
    $db['mydb2']['stricton'] = FALSE;
    
  2. Now we use new database.

    $CI = &get_instance();
    $this->db2 = $CI->load->database('mydb2', TRUE);
    $qry = $this->db2->query("SELECT * FROM employee");
    print_r($qry->result());