繁体   English   中英

动态数据库切换-Codeigniter

[英]Dynamic Database Switch - Codeigniter

我想在运行时切换我的codeigniter多个数据库。 我的默认数据库将在该页面上完全运行,但是当我需要根据场景或要求切换到其他数据库时,我可以这样做。 通用模型功能将适用于所有不同的数据库。 因此,我想使用动态选择器在不使用会话或不传递函数变量的情况下对多个数据库连接使用相同的模型和相同的函数

为了达到这个目的,我在cofig中设置了一个名称,当我调用模型时,在调用model之前在控制器中设置了所需的数据库名称,然后尝试在controller中设置的model中获得名称。 但是不幸的是我没有从控制器到模型的名字。

数据库配置文件-

$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();
   }

这是我尝试切换数据库的方式。 如果你们有其他最佳的解决方案来切换多个数据库,那么请随时向我建议。

尝试以下示例以动态配置另一个数据库

普通模型

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_master表,该表通过传递GroupId来获取逐组数据库详细信息。I获取记录并根据组设置另一个数据库确保您存储在数据库中的所有数据库配置信息都是加密格式 。其他数据库

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM