2015-04-15 66 views
0

我在codeigniter中創建了一個項目,但該項目有多個DBS。它運作良好,但我期待調用一個DB依賴於database.php中的文件我想加載用戶表的詳細信息在codeigniter的database.php中獲取SESSION值

會話的用戶名來查詢

我做了以下

$autoload['libraries'] = array('session'); 

if(!empty($this->session->userdata('username'))) 
$username_c = $this->session->userdata('username'); 

我做錯了什麼?

+1

如果我們正在談論'APPPATH,那麼你不應該在'database.php'文件中這樣做。 'config/database.php',但是在部分代碼中設置了相應的數據庫。 – Tpojka

回答

0

正如@Tpojka在評論中說的,你不應該在database.php。您可以動態選擇數據庫並在查詢之前獲取實例。檢查here

$db['default']['hostname'] = "localhost"; 
$db['default']['username'] = "root"; 
$db['default']['password'] = ""; 
$db['default']['database'] = "db_one"; 
$db['default']['dbdriver'] = "mysql"; 
$db['default']['dbprefix'] = ""; 
$db['default']['pconnect'] = TRUE; 
$db['default']['db_debug'] = FALSE; 
$db['default']['cache_on'] = FALSE; 
$db['default']['cachedir'] = ""; 
$db['default']['char_set'] = "utf8"; 
$db['default']['dbcollat'] = "utf8_general_ci"; 
$db['default']['swap_pre'] = ""; 
$db['default']['autoinit'] = TRUE; 
$db['default']['stricton'] = FALSE; 


$db['second_db']['hostname'] = "localhost"; 
$db['second_db']['username'] = "root"; 
$db['second_db']['password'] = ""; 
$db['second_db']['database'] = "db_two"; 
$db['second_db']['dbdriver'] = "mysql"; 
$db['second_db']['dbprefix'] = ""; 
$db['second_db']['pconnect'] = TRUE; 
$db['second_db']['db_debug'] = FALSE; 
$db['second_db']['cache_on'] = FALSE; 
$db['second_db']['cachedir'] = ""; 
$db['second_db']['char_set'] = "utf8"; 
$db['second_db']['dbcollat'] = "utf8_general_ci"; 
$db['second_db']['swap_pre'] = ""; 
$db['second_db']['autoinit'] = TRUE; 
$db['second_db']['stricton'] = FALSE; 

在模型中,

public function get_profile() { 
    if(!empty($this->session->userdata('username'))) { 
     $username_c = $this->session->userdata('username'); 
     $DB2 = $this->load->database('second_db', TRUE); // true to get db instance 
     return $DB2->select("*")->from("user")->get()->row(); // query from second DB 
    } 

    $this->db->select("*")->from("user")->get()->row(); // query from default DB 
} 

希望這將是對你有用。

相關問題