SWahi
SWahi

Reputation: 88

Codeigniter 3.0 - Can't change database connection dynamically

I want to change the database connection dynamically, I succeded in codeigniter 2.2.0 but not in 3.0 version.

Here's my code :

public function index(){
        $this->load->model('compte_model','compte');
        $this->load->model('utilisateur_model','utilisateur');
        $this->load->helper('database_helper');

        //Getting the database where to connect from the principale database
        $compte = $this->compte->get_by('nom',$this->input->get('nom'));
        $bdd = $compte->bdd_principale;

        //Get the new configuration
        $newDBB = getGroupName($bdd);
        $this->load->database($newDBB,TRUE);

        //Made a query in the second database but it doesn't work
        $users = $this->utilisateur->get_all();

        return $users;
    }

Here's the helper function :

function getGroupName($bdd){
    $config['hostname'] = "localhost";
    $config['username'] = "root";
    $config['password'] = "";
    $config['database'] = $bdd;
    $config['dbdriver'] = "mysql";
    $config['dbprefix'] = "";
    $config['pconnect'] = TRUE;
    $config['db_debug'] = TRUE;
    $config['cache_on'] = FALSE;
    $config['cachedir'] = "";
    $config['char_set'] = "utf8";
    $config['dbcollat'] = "utf8_general_ci";    

    return $config;
}

Upvotes: 0

Views: 762

Answers (1)

SWahi
SWahi

Reputation: 88

After some tests, I've found the solution:

  • First of all, the model in the second database have to be loaded after changing the database configuration.
  • Second, we have to send parametres of database, as FALSE for the returning and TRUE for query_builder.

Finally, the code will be like this:

public function index_get(){
        $this->load->model('compte_model','compte');
        $this->load->helper('database_helper');

        $compte = $this->compte->get_by('nom',$this->input->get('nom'));
        $bdd = $compte->bdd_principale;

        //Get the new configuration
        $newDBB = getGroupName($bdd);
        $this->load->database($newDBB,FALSE,TRUE);

        $this->load->model('utilisateur_model','utilisateur');

        $users = $this->utilisateur->get_all();

        return $users;
    }

The reason to send this parametres is to change the '$this->db' instance.

Upvotes: 1

Related Questions