php动态数据库开关codeigniter

i7uq4tfw  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(290)

我想在运行时切换我的codeigniter多数据库。我的默认数据库将在整个页面上运行,但当我需要根据场景或需求切换到其他数据库时,我可以这样做。通用模型函数将适用于所有不同的数据库。所以,我希望使用动态选择器,在不使用会话或不传递函数变量的情况下,对多个数据库连接使用相同的模型和函数
为了实现这一点,我在cofig中设置了一个名称,当我调用我的模型时,我在调用模型之前在controller中设置了所需的数据库名称,然后我尝试在model中获取在controller中设置的名称。但不幸的是,我没有从控制器到模型的名称。
数据库配置文件-

$db['default'] = array(
               'dsn'    => '',
               'hostname' => 'localhost',
               'username' => 'root',
               'password' => 'pass'
               'database' => 'db1'
                .......
               );

$db['anotherDB'] = array(
               'dsn'    => '',
               'hostname' => 'localhost',
               'username' => 'root',
               'password' => 'pass'
               'database' => 'db2'
                .......
               );

控制器-

$this->config->set_item('active_db', 'anotherDB');
$sql = 'select * from user';
$anotherDB_record = $this->model->customQuery($sql);

print_r($anotherDB_record);

$this->config->set_item('active_db', 'default');
$sql = 'select * from customer';
$default_record = $this->model->customQuery($sql);

print_r($default_record);

模式-

protected $database;
   function __construct() {
       parent::__construct();
       $oDB = $this->config->item('active_db');
       $this->database = $this->load->database($oDB, TRUE);
   }    
   function customQuery($sql){
       $query = $this->database->query( $sql );
       return $query->result();
   }

这就是我试图切换数据库的方式。如果你们有任何其他最好的解决方案,切换多个数据库,然后请随时建议我。

swvgeqrz

swvgeqrz1#

尝试下面的例子来动态配置另一个数据库
通用模型

function getOtherDB($groupID) {
    $getRecord = $this->common_model->getRow('group_master', 'GroupID', $groupID);
    if ($getRecord) {
        $config['database'] = $getRecord->DBName;
        $config['hostname'] = $getRecord->DBHostIP;
        $config['username'] = $getRecord->DBHostUName;
        $config['password'] = $getRecord->DBHostPassw;
        $config['dbdriver'] = "mysqli";
        $config['dbprefix'] = "";
        $config['pconnect'] = FALSE;
        $config['db_debug'] = TRUE;
        $DB2 = $this->load->database($config, TRUE);
        if ($DB2) {
            return $DB2;
        }
    }
    return FALSE;
}

在上面的例子中,我有group\主表,它有group wise数据库的详细信息,通过传递groupid,我获取记录并根据group设置另一个数据库确保存储在数据库中的所有数据库配置信息都是加密格式使用下面的例子对其他数据库进行查询

$result = $DB2->query("select * from group");
// $DB2 is other database instance you can create multiple db connection using above methos

相关问题