使用codeigniter防止在插入和更新时重复输入

时间:2013-11-11 09:40:59

标签: codeigniter

我正在尝试使用codeigniter停止数据库中的重复输入。它在我插入数据时工作正常,但是当我更新数据时它不起作用。如果我只更改描述而不是部门名称,则它已经存在消息。

为此我在控制器中使用波纹管代码:

$ this-> form_validation-> set_rules('departmentname','Departmentname','trim | required | xss_clean | is_unique [department_master.departmentname]');

2 个答案:

答案 0 :(得分:0)

您必须编写验证码。

方法1:验证回调

您的规则声明:

$this->form_validation->set_rules('field', 'label', 'callback__is_unique2');

该方法,在与验证相同的控制器中:

public function _is_unique2($input) {
    $exclude_id = $this->input->post('id');

    if( $this->db->where('departmentname', $input)->where('id !=', $exclude_id)
        ->limit(1)->get('department_master')->num_rows())
    {
        $this->form_validation->set_message('_is_unique2', 'name exists');
        return FALSE;
    }

    return TRUE;
}

Callbacks: Your own Validation Functions

方法2:扩展Form_validation以添加新的验证规则

您的规则声明:

$exlclude_id = $this->input->post('id');

$this->form_validation->set_rules('field', 'label',
 'is_unique2[department_master.departmentname.id_field.'.$exclude_id.']');

Form_validation的扩展,

//Libraries/MY_Form_validation.php

class MY_Form_validation extends CI_Form_validation {

    public function __construct() {
        parent::__construct();
    }

    public function is_unique2($str, $field)
    {
        list($table, $field, $exclude_field, $exclude_value)=explode('.', $field);

        return (bool) $this->CI->db
            ->where($field, $str)
            ->where($exclude_field.' !=', $exclude_value)
            ->limit(1)
            ->get($table)->num_rows();
    }

}

Extending Native Libraries

*没有经过测试的代码

答案 1 :(得分:0)

  

您可以在验证规则中使用回调函数。例如

$this->form_validation->set_rules('departmentname', 'Departmentname', 'trim|required|xss_clean|is_unique[department_master.departmentname]|**callback_is_unique_department**');
Callback function take first argument in a function is field value itself.

public function is_unique_department($dep_name)
{
   // select query which find same department value exists or not if exists then write

    $this->form_validation->set_message('is_unique_department', 'This Department Name is already exists.');
     return false;

   else write return false

}