Reputation: 88
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
Reputation: 88
After some tests, I've found the solution:
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