CodeIgniter - is_unique 表单验证规则无法正常工作

CodeIgniter - is_unique form validation rule not working right

我有一个表格要提交到我的数据库。如果不使用 is_unique 验证规则,它会完美运行。当我尝试将它放入我的代码中时,我收到一条错误消息,指出我尝试使用它的每个字段都需要一个唯一值。问题是我正在将数据插入我的数据库,而我知道这些数据还不存在。这是我的代码:

控制器:

function submit_register() {

        $this->load->library('form_validation');

        $this->form_validation->set_rules('first_name', 'First Name', 'required|max_length[30]|xss_clean');
        $this->form_validation->set_rules('last_name', 'Last Name', 'required|max_length[30]|xss_clean');
        $this->form_validation->set_rules('email', 'E-Mail', 'required|max_length[30]|valid_email|is_unique[users.email]|xss_clean');
        $this->form_validation->set_rules('username', 'Username', 'required|max_length[30]|is_unique[users.username]|xss_clean');
        $this->form_validation->set_rules('password', 'Password', 'required|max_length[30]|xss_clean');
        $this->form_validation->set_rules('password_confirmation', 'Password Confirmation', 'required|max_length[30]|matches[password]|xss_clean');

        if ($this->form_validation->run($this) == FALSE) {
                $this->register();
        }
        else {
                $data = array(
                'first_name' => $this->input->post('first_name'),
                'last_name' => $this->input->post('last_name'),
                'email' => $this->input->post('email'),
                'username' => $this->input->post('username'),
                'password' => $this->input->post('password'),
                );
                $this->load->model('mdl_users');
                $this->mdl_users->_register_user($data);
                redirect("http://localhost:8888");
        }
    }

型号:

function _register_user($data) {
        $salt = bin2hex(openssl_random_pseudo_bytes(22));
        $encrypted_password = md5($data['password'].''.$salt);

        $data = array(
            'first_name' => $data['first_name'],
            'last_name'  => $data['last_name'],
            'email'      => $data['email'],
            'username'   => $data['username'],
            'password'   => $encrypted_password,
            'salt'       => $salt,
            'user_level' => 'user',
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        );

        $this->db->insert('users', $data);
        }

我在 CodeIgniter 手册中读到:

Note: This rule requires Query Builder to be enabled in order to work.

这就是我所缺少的吗?如果是这样,我找不到如何执行此操作的答案。

你错过了吗?

$this->load->library('database');

您可以使用此视图来检查 is_unique 是否有效。

<?php if(validation_errors()) echo validation_errors(); ?>

Yachi 的回答很好,但是如果你想在控制器内部手动连接数据库,你必须使用这个:

$this->load->database();

This is wrong: $this->load->library('database');