[英]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.