Wednesday 21 March 2012

Create Multiple Databases Connections in Codeigniter


// To connect to Multiple Databases Connection in Codeigniter
// Open config/database.php and build the db connection array.

// This is for default database.
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'db_default';
........
.......

// This is for second database database.
$db['db2']['hostname'] = 'localhost';
$db['db2']['username'] = 'root';
$db['db2']['password'] = '';
$db['db2']['database'] = 'database2';
........
.......
Now, open your model files and create the db instance as per needs for second database.

class Rc_model extends CI_Model {
 private $db2; 
 public function Rc_model()
 {
  parent::__construct();
  // $this->db; // this is for default database connection.
  // $this->db = $this->load->database(); // this is also for default connection if you need a db instance.
  // Creating the db object for Second Database whose connection is available globally.
  $this->db2 = $this->load->database('db2', TRUE);
  $this->db2 =& $this->db2;
 }

 public function GetAllCategories()
 {
  $query = $this->db2->get_where('categories_table', array('active'=>'1'));
  return $query->result();
 }
}

No comments:

Post a Comment

Please post any queries and comments here.