phpmysqlformscodeigniterhmvc

CodeIgniter - is_unique form validation rule not working right


I have a form I am trying to submit to my database. It works perfectly if don't use the is_unique validation rule. When I try to put this into my code I get an error saying that each field I try to use it for needs a unique value. The problem is I am inserting data into my database that I know is not in there already. Here is my code:

Controller:

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");
        }
    }

Model:

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);
        }

I read this in the CodeIgniter manual:

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

Is this what I am missing? If so I can't find the answer on how to do this.


Solution

  • Did you miss this?

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

    You can use this in view to check is_unique is work or not.

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