2012-02-02 48 views
0

這裏是我的控制器笨 - 查詢返回1行,即使沒有數據來匹配

public function login() { 
    $this->load->model('admin_model'); 

    $access = $this->admin_model->check_login(); 
    $data['content'] = 'content/home'; 
    $data['title'] = 'Admin Panel Login'; 

    if($access) { 
     $data= array(
      'email' => $this->input->post('email'), 
      'is_logged_in' => true 
     ); 
     $this->session->set_userdata($data); 
     redirect('admin/index/dashboard'); 
    } else { 
     $this->index($page = 'home', $msg = 'failure'); 
} 

這裏是我的模型

public function check_login() { 
    $this->db->where('email', $this->input->post('email')); 
    $this->db->where('password', $this->input->post('password')); 
    $query = $this->db->get('customers'); 

    return (bool) $query->num_rows; 
} 

所以,我一直在爲一個功能我的Admin構造函數將確保用戶在登錄之前不能訪問任何頁面。問題是,當我去管理員/登錄時,它將is_logged_in設置爲true,即使check_login函數應該返回爲false。這是說,它正在發現一排,即使我的數據庫中只有1行現在應該不匹配。

我是新來的CI,所以請溫柔。 :)

回答

2

num_rows()是方法(不是屬性),應該使用更多的是這樣的:

return $query->num_rows() > 0; 
+0

即使在調整我的代碼後,它不起作用。它正在做的查詢是: SELECT * FROM ('客戶') 其中'email' = 0 和'password' = 0 和它的返回check_login()是真的。 (0和0是默認發佈的內容)也許我組織不正確? – ohiock 2012-02-02 15:47:45

+0

您可以直接針對您的數據庫(CI之外)運行該查詢並查看返回的內容嗎? – 2012-02-02 16:03:59

+0

當然。以下是輸出結果:「顯示行0 - 0(總共1次,查詢花費0.0004秒)」。我似乎無法弄清楚爲什麼$訪問迴歸爲真。 – ohiock 2012-02-02 16:18:41

1

科林的答案的擴展:

public function check_login() { 
    $this->db->where('email', $this->input->post('email')); 
    $this->db->where('password', $this->input->post('password')); 
    $query = $this->db->get('customers'); 

    if ($query->num_rows()>0) { 
     return TRUE; 
    } else { 
     return FALSE; 
    } 
} 
+0

是的,我也試過這個。問題不在於我錯誤地編寫了我的條件語句,而是它返回了1行,即使它不應該。當我直接進入管理員/登錄時,它的行爲就好像我提交了數據(這將是0和0),因此它返回true,而不應該是。 – ohiock 2012-02-02 15:53:58

0

我沒有看到這一點在你的模型中。

模型不能(或者即使它可以,不應該)從視圖中獲取變量。它應該通過控制器來。

你確定,後期變量出現在模型中嗎?

更好的解決方案。在控制器中捕獲post變量。

在模型中,使用參數創建函數。

然後在控制器中,像這樣檢索它。

$data['bla'] = $this->admin_model->method_name($this->input->post('blabla')); 

這將防止所有這些混淆。

+0

是的,我之前安排過它。兩者工作相同,但我會再調整一次。 – ohiock 2012-02-02 16:41:57

相關問題