2013-12-12 86 views
0

我使用codeigniter创建注册表单。我知道在CI中每个字段都有一个验证,但我想要做的是验证多个字段是否存在。如何使用codeigniter检查记录是否存在

SELECT emp_id FROM emp_record WHERE firstname = 'firstname' AND lastname = 'firstname' AND birthdate = 'firstname' 

如果上面的查询找到匹配我想在我的视图页上提醒该记录已经存在。

请帮忙。

欣赏它。谢谢。

回答

0

你可以使用num_rows()来做这样的事情。 通过使用活动记录您可以通过以下

$qry = $this->db->select('emp_id')->from('emp_record') 
      ->where('firstname', $firstname) 
      ->where('lastname', $lastname) 
      ->where('birthdate', $birthdate) 
      ->get(); 

if ($qry->num_rows() > 0) 
    return TRUE; 
else 
    return FALSE; 

如果发现数据库中的至少一个排或FALSE如果发现任何内容,则返回TRUE实现这一目标。

1

声明一个自定义的回调函数

function _check_firstname() 
{ 
    $firstname = $this->security->xss_clean($this->input->post('firstname')); 
    $array = array('firstname' => $firstname, 'birthdate' => $firstname); 
    $result = $this->db->select('emp_id')->from('emp_record')->where($array)->get(); 
    if($result->num_rows()) 
    { 
     $this->form_validation->set_message('_check_firstname', 'Record already exists'); 
     return false; 
    }else 
    { 
     return true; 
    } 
} 

设置规则,包括(callback__check_firstname

$this->form_validation->set_rules('firstname', 'First Name', 'trim|required|callback__check_firstname'); 

现在,当你喜欢

if ($this->form_validation->run()){ 
    // passes 
} 
else{ 
    // not passes, so show the view again 
} 

检查验证在视图中,如果你有这样的事情

<?php echo form_error('firstname') ?> 

这将显示自定义回调函数中设置的错误消息。

0

有些人可能/可能具有相同的名字,姓氏和出生日期

但还是如果你想有这样的说法,你可以创建一个callback validation

这里是一个片段。

public function checkinput() 
{ 
    // you may want to sanitize the input 
    $data['fname'] = $this->input->post('fname'); 
    $data['lname'] = $this->input->post('fname'); 
    $data['mname'] = $this->input->post('fname'); 

    //your model for checking data must return TRUE or FALSE 
    if($this->model->method_for_checking($data)) 
    { 
    this->form_validation->set_message('checkinput', 'Duplicate data exists.'); 
    return TRUE; 
    }else{ 
    return FALSE; 
    } 
} 

现在你可以使用它在你的验证规则,即

$this->form_validation('fname','fname',callback_checkinput);

其他选项是

  1. 扩展表单验证,并在其中创建一个验证规则不 杂波控制器
  2. 或者,在插入之前提交表单之后数据,你可以检查它是否是重复的,并且做他们的逻辑事物。
相关问题