根据登录用户的凭据动态切换到不同的数据库?

时间:2017-02-08 04:24:01

标签: php mysql codeigniter

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

可以访问多个数据库。对于每个分支,都有一个动态创建的数据库。每个分支都有一个帐户。登录帐户后,将访问与该帐户相关的数据库。然后,该数据库将用于整个会话,直到用户注销。

我有一个主数据库,其中存储了有效用户名/密码组合的主列表。我在database.php文件夹的config中声明了这一点。但是在用户登录后,我将需要切换到与该用户帐户相关的数据库,以便他们可以访问他们的数据。

如何将此控制器用于我的模型,以便它们都能访问同一个数据库(无需反复重做$this->load->database())?

1 个答案:

答案 0 :(得分:0)

在您的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
    );
}