我有一个要提交到数据库的表格。如果不使用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(); ?>