我想动态更改数据库连接,我在codeigniter 2.2.0中成功但在3.0版本中没有。
这是我的代码:
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;
}
这是辅助函数:
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;
}
答案 0 :(得分:1)
经过一些测试,我找到了解决方案:
最后,代码将是这样的:
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;
}
发送此参数的原因是更改' $ this-> db'实例