如何根据用户的登录凭据连接到不同的数据库?
db_helper.php
<?php
function setDb($company_name, $branch_name) {
return array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => $company_name.'_'.$branch_name,
'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
);
}
?>
Select_db.php (/libraries) --> 包含在 autoload.php 中
<?php
class Select_db {
public function thisdb($db_settings) {
return $this->load->database($db_settings, TRUE);
}
}
?>
model.php(我这里好像报错了,但是打印不出来)
if ($result_num == 1) {
$first_row = $query->row();
$stored_password = $first_row->password;
if (crypt($password, $stored_password) == $stored_password) {
//Successful login
$sql = "SELECT
company.name As company_name,
branch.name As branch_name,
branch.id As branch_id
FROM
account
INNER JOIN
branch
ON
account.branch_id = branch.id
INNER JOIN
company
ON
branch.company_id = company.id
WHERE
account.username = ?
";
$query = $this->db->query($sql, $username);
$data = array();
$data['company_name'] = $query->row()->company_name;
$data['branch_id'] = $query->row()->branch_id;
$branch_name = $query->row()->branch_name;
$this->load->helper('db_helper');
$db_settings = setDb($data['company_name'], $branch_name);
$dbname = $data['company_name'].'_'.$branch_name;
//$dsn = 'dbdriver://root:sprinthr123@localhost/'.$dbname;
//$this->branch_db = $this->load->database($dsn);
//I'm guessing the error is somewhere around here
//because when I comment it out I don't get the 500 error
//code anymore and I'm able to log in to the homepage
$db = $this->Select_db->thisdb($db_settings);
} else {
return FALSE;
}
} else {
return 0;
}
当通过 AJAX 请求登录时调用此模型。我在控制台中收到一个 500
错误代码,所以肯定有一些错误,但我不知道错误在哪里?
它必须是动态的,所以我不能简单地在配置中填充 database.php 文件。
最佳答案
在config目录下的database.php中添加这一行
/********* For Other Database***********************/
$db['Other']['hostname'] = '192.168.1.191';
$db['Other']['username'] = 'user589';
$db['Other']['password'] = 'pass12345';
$db['Other']['database'] = 'other_db';
$db['Other']['dbdriver'] = 'mysql';
$db['Other']['dbprefix'] = '';
$db['Other']['pconnect'] = TRUE;
$db['Other']['db_debug'] = TRUE;
$db['Other']['cache_on'] = FALSE;
$db['Other']['cachedir'] = '';
$db['Other']['char_set'] = 'utf8';
$db['Other']['dbcollat'] = 'utf8_general_ci';
$db['Other']['swap_pre'] = '';
$db['Other']['autoinit'] = TRUE;
$db['Other']['stricton'] = FALSE;
在模型中使用“其他”数据库配置
public function get_a_queue() {
$otherdb = $this->load->database('Other', TRUE); //loaad second databse
$qr = $otherdb ->query("SELECT * from users");
return $qr->result();
}
希望对你有帮助
关于php - 登录后连接到不同的数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42267418/