1
如何根據用戶的登錄憑據連接到不同的數據庫?登錄後連接到其他數據庫?
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(/庫) - >包括在autoload.php
<?php
class Select_db {
public function thisdb($db_settings) {
return $this->load->database($db_settings, TRUE);
}
}
?>
model.php(I似乎是在這裏得到一個錯誤,但我不能打印出來)
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:[email protected]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
錯誤代碼,所以一定有一些錯誤,但我不知道在哪裏?
它必須是動態的,所以我不能只是簡單地在config中填充database.php文件。
請參閱此HTTPS:/ /codeigniter.com/user_guide/database/configuration.html – Naincy
它必須是動態的嗎?因爲有多個數據庫可以訪問。哪一個將被訪問取決於成功登錄的用戶名(已經涵蓋)。主要問題是建立連接。 @Naincy – herondale
你寫連接腳本並建立連接。成功登錄後關閉所有其他數據庫連接(PHP函數)並啓用只有你想要的。希望這會有所幫助 –