Codeigniter 3.0 - 无法动态更改数据库连接

时间:2015-04-23 10:10:26

标签: php database codeigniter

我想动态更改数据库连接,我在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;
}

1 个答案:

答案 0 :(得分:1)

经过一些测试,我找到了解决方案:

  • 首先,必须加载第二个数据库中的模型 更改数据库配置后。
  • 其次,我们必须发送数据库的参数,为FALSE 对于query_builder,返回TRUE。

最后,代码将是这样的:

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'实例