Create Multiple Database Connection in Codeigniter

In this post we have explained about how to create multiple database connection in codeigniter. Please do the following changes in your files.

Config.php:

Change the below following things in your config.php

$active_group = 'default';
$active_record = TRUE;

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';    
$db['default']['database'] = 'demo_users';    
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

$db['test_users_db']['hostname'] = 'localhost';
$db['test_users_db']['username'] = 'root';
$db['test_users_db']['password'] = '';
$db['test_users_db']['database'] = 'test_users';
$db['test_users_db']['dbdriver'] = 'mysql';
$db['test_users_db']['dbprefix'] = '';
$db['test_users_db']['pconnect'] = TRUE;
$db['test_users_db']['db_debug'] = TRUE;
$db['test_users_db']['cache_on'] = FALSE;
$db['test_users_db']['cachedir'] = '';
$db['test_users_db']['char_set'] = 'utf8';
$db['test_users_db']['dbcollat'] = 'utf8_general_ci';
$db['test_users_db']['swap_pre'] = '';
$db['test_users_db']['autoinit'] = FALSE;
$db['test_users_db']['stricton'] = FALSE;

users_model.php:

Here we give sample example code of model function i hope this way you can optimize your functions.

function get_users($id){
    $CI         =& get_instance();
    $survey_db    =     $CI->load->database('test_users_db', TRUE);        
    $sql        =    "SELECT username FROM users where user_id = '$id'";
    $query        =    $survey_db->query($sql);            
    $survey_db->close();
    $CI->load->database('default', true);
    $row        =    $query->row();
    return $row->username;
}

 

Comments

comments

phpexpertise

I’m Blogger and Programming Blog, Tutorials, PHP, MySQL, jQuery, Laravel, Wordpress and Codeigniter