w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Codeigniter - Where to create the second database connection?

You could extend the CI_Model for this purpose. First create a base model under application/core say MY_Model.php. The prefix MY_ depends on a variable $config['subclass_prefix'] = 'MY_'; in the config file.

MY_Model.php

class MY_Model extends CI_Model{
 protected $myDB =null;

 public function __construct(){
        $this->connect_db();
 } 

 public function connect_db(){
       /***First fetch the configuration here from dm_masterdb 
           and assign it to the following array as needed ***/

        //assign the values
        $userDbConfig['hostname'] ='fetched value from above';
         ...................................
        $userDbConfig['dbcollat'] = "utf8_general_ci";  
        $this->myDB = $this->load->database($userDbConfig, TRUE);
 }

}

Now under your models folder , say you have a model called test_model

test_model.php

class Test_model extends MY_Model
{


    function __construct()
    {
        parent::__construct();
    }
    public function get_result(){
        $t = $this->db->query('query on default
db')->result_array();
        $t1 = $this->myDB->query('query on your dynamic
db')->result_array();
        echo "<pre>";
        print_r($t1);
        print_r($t);

    }
}

Hope this helps you...





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.