![](/img/trans.png)
[英]How Switch User And Backup A DataBase In MySql With Current User(Logged In User)?
[英]make dynamic switch to different database based on logged in user's credentials?
為database.php
<?php
class Database extends CI_Controller {
public $branch_db;
function __construct($company_name, $branch_name) {
parent::__construct();
$branch_db = $this->load->database($company_name.'_db_'.$branch_name);
}
}
?>
Account_model.php
protected function verifyLogin($username, $password) {
$this->db->trans_start();
$sql = "SELECT password, company_id, branch_id
FROM account
WHERE username = {$username}"; //Prepare statement
$query = $this->db->query($sql);
$result_num = $query->num_rows();
if ($result_num == 1) {
$first_row = $query->row();
$stored_password = $first_row->password;
if (password_verify($password, $stored_password)) {
//Successful login
//Get company name
//Get branch name
//Set database
//Pass company_name, branch_name
//All models must be able to access the dynamically loaded database
}
}
$this->db->trans_complete();
}
有多個數據庫可以訪問。 對於每個分支,都有一個動態創建的數據庫。 每個分支都有一個帳戶。 登錄帳戶后,將訪問與該帳戶相關的數據庫。 然后,該數據庫將用於整個會話,直到用戶注銷為止。
我有一個主數據庫,其中存儲了有效的用戶名/密碼組合的主列表。 我在config
文件夾中的database.php
中聲明了它。 但是在用戶登錄后,我將需要切換到與該用戶帳戶相關的數據庫,以便他們可以訪問其數據。
如何為模型使用此控制器,以便它們都訪問同一數據庫(而不必一遍又一遍地重做$this->load->database()
)?
我期望在您的database.php Application->config->database.php
,您創建一個會話並在登錄時存儲admin_type變量。
$admin_type = $this->session->userdata['admin_type'];
$active_group = 'default';
$query_builder = TRUE;
if ($admin_type==1) {
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => 'root',
'database' => 'name_db',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
}else{
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => 'root',
'database' => 'name_db2',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.