如何使用codeigniter检查记录是否存在

时间:2013-12-12 12:12:45

标签: codeigniter

我正在使用codeigniter创建注册表单。我知道CI中的每个字段都有验证,但我想要做的是验证存在多个字段。

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

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

请帮忙。

欣赏它。感谢。

3 个答案:

答案 0 :(得分: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') ?>

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

答案 1 :(得分: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;

如果它在数据库中找到至少一行,则返回TRUE;如果找不到任何行,则返回FALSE。

答案 2 :(得分: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. 或者,在插入数据之前提交表单之后,您可以检查它是否重复并执行逻辑事务。
相关问题