2015-10-22 25 views
1

我需要幫助,瞭解如何檢查數據庫中是否存在名字和姓氏,然後使用codeiginiter調用回調。我現在完全被卡住了。順便提一下,名字和姓氏是兩個不同的字段。謝謝Codeigniter回調阻止添加重複的名字和姓氏

public function check_duplicate($str,$col) 
     { 
      $res = $this->db->get_where("patients",array(
       'firstname' => 'Firstname', 
       'lastname' => 'Lastname' 
       )); 
      if($res->num_rows()){ 
       $this->form_validation->set_message('check_duplicate', 'The %s field already exists.'); 
       return false; 
      } else { 
       return true; 
      } 
     } 

回答

1

不需要回調。您可以改用is_unique

$this->form_validation->set_rules("firstname","First Name"."required|is_unique[tablename.columnname]"); 
$this->form_validation->set_rules("lastname","last Name"."required|is_unique[tablename.columnname]"); 

或者,如果你想使用回調,使用,

$this->form_validation->set_rules("firstname","First Name"."required|callback_check_name"); 

public function check_name($str) 
{ 
    $res = $this->db->get_where("users",array("fname" => $str)); 
    if($res->num_rows()){ 
     $this->form_validation->set_message('check_name', 'The %s field already exists.'); 
     return false; 
    } else { 
     return true; 
    } 
} 

所以,現在你必須寫2個回調函數來處理表單驗證。你可以像這樣只有一個回調。

$this->form_validation->set_rules("firstname","First Name"."required|callback_check_name[firstname]"); 

$this->form_validation->set_rules("firstname","First Name"."required|callback_check_name[lastname]"); 

public function check_name($str,$col)//passing one more parameter. 
{ 
    $res = $this->db->get_where("users",array($col => $str)); 
    if($res->num_rows()){ 
     $this->form_validation->set_message('check_name', 'The %s field already exists.'); 
     return false; 
    } else { 
     return true; 
    } 
} 
+0

我想你的意見,但仍然沒有工作的鏈接。相反,我換成了「。」用「,」和現在系統表示「姓氏字段必須包含一個唯一值。 名字字段必須包含一個唯一值。」 – claudios

+0

你有沒有改變表名和列名? –

+0

您嘗試過哪種方法? 'is_unique'或'callbacks'? –