Selasa, 07 Mei 2013

How to connect multiple databases in codeigniter


1. There are two ways to connect the database
  • Automatic connecting
The “automatic connection” feature will load and instantiate the database class with every page load. To enable “auto connecting”, add the word database to the library array, as indicated in the following file: application/config/autoload.php
$autoload['libraries'] = array('database');
  • Manually connecting
By using the below function for manual connection.
$this->load->database();
If you want to connect multiple databases then go to manual connection.

2. First configure two database details in database.php file under the application -> config folder like below
First database details
$active_group = 'default';
$active_record = TRUE;
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'table1';
$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'] = '';

Second database details
$active_group = ‘forum’;
$active_record = TRUE;
$db['forum']['hostname'] = ‘localhost’;
$db['forum']['username'] = ‘root’;
$db['forum']['password'] = ”;
$db['forum']['database'] = ‘table2′;
$db['forum']['dbdriver'] = ‘mysql’;
$db['forum']['dbprefix'] = ”;
$db['forum']['pconnect'] = TRUE;
$db['forum']['db_debug'] = TRUE;
$db['forum']['cache_on'] = FALSE;
$db['forum']['cachedir'] = ”;
$db['forum']['char_set'] = ‘utf8′;
$db['forum']['dbcollat'] = ‘utf8_general_ci’;
$db['forum']['swap_pre'] = ”;

3. Below script for controller file
public function index(){
$this->load->model('Samplemodel');
//Load first database and call it’s related queries
$this->db_forum = $this->load->database('forum', TRUE);
$data[‘first_reg’] = $this->Samplemodel->get_details_one();
//Load second database and call it’s related queries
$this->db = $this->load->database('default', TRUE);
$data[‘second_reg’] = $this->Samplemodel->get_details_two();
$this->load->view('welcome_message',$data);
}


4. Below script for model file
class Samplemodel extends CI_Model {
function __construct(){
parent::__construct();
}
function get_details_one(){
$query = $this->db_forum->get('jos_users');
return $query->result();
}
function get_details_two(){
$query = $this->db->get('engine4_user_logins', 10);
return $query->result();
}
}


5. Display output in view page
print_r($first_reg);
echo '<br> <br>';
print_r($second_reg);


Sumber : http://blog.4frienz.com/how-to-connect-multiple-databases-in-codeigniter.html

Tidak ada komentar:

Posting Komentar