我在codeigniter的一个站点上工作。我不太擅长使用框架。在这里,我必须检查数据库中是否已经存在电子邮件。我已经对所需的功能进行了编码,但在提交表单时出现了错误。在控制器中,我制定了以下规则。
我的代码是:
$this->form_validation->set_rules(
'email', 'Email', 'trim|required|valid_email|is_unique|callback_isEmailExist'
);
public function isEmailExist($email) {
$this->load->library('form_validation');
$this->load->model('user');
$is_exist = $this->user->isEmailExist($email);
if ($is_exist) {
$this->form_validation->set_message(
'isEmailExist', 'Email address is already exist.'
);
return false;
} else {
return true;
}
}
在模型用户中,功能是:
function isEmailExist($email) {
$this->db->select('id');
$this->db->where('email', $email);
$query = $this->db->get('users');
if ($query->num_rows() > 0) {
return true;
} else {
return false;
}
}
当我提交表格时,我收到了以下错误。
遇到PHP错误
严重性:通知
消息:未定义偏移:1
文件名:librarys/Form_validation.php
行号:953
发生数据库错误
错误编号:1064
您的SQL语法有错误;查看与MySQL服务器版本相对应的手册,了解在'WHERE`='附近使用的正确语法muraddnw@gmail.com第2行的"极限1"
选择*,其中`='muraddnw@gmail.com'限制1
文件名:C:''examplep''htdocs''auction''system''database''DB_driver.php
行号:330请任何人帮帮我。提前谢谢。
您的问题在set_rules行。在这里,您同时使用is_unique
和callback
函数。你必须使用任何一个。如果您使用call_back函数来检查重复的数据;不需要使用is_unique。For this wrong you get that error
只需从中移除is_unique
即可。
$this->form_validation->set_rules('email','Email','trim|required|valid_email|callback_isEmailExist'); // removed is_unique
试试这个,让我知道。
$this->form_validation->set_rules('username', 'userName', 'required|callback_exists_username');
#uniqueness of username
function exists_username($str)
{
$record_id = $this->input->post('record_id');
$condition = array('user_id !='=>$record_id,'username'=>$str);
$value =GetAllRecord('user_master',$condition,$is_single=true);
if (count($value) == 0)
{
return TRUE;
}
else
{
$this->form_validation->set_message('exists_username', 'username already exists!');
return FALSE;
}
}
只需将is_unique[tablename.fieldname]
规则添加到表单验证中。例如:
array('field' => 'email', 'label' => 'Email', 'rules' => 'trim|required|valid_email|is_unique[users.email]'));
您的模型就像
$this->db->select('id');
$this->db->where('email', $email);
请告诉mysql您想从哪个表中获取记录。
$this->db->from('tablename');
就像
$this->db->select('id');
$this->db->from('tablename');
$this->db->where('email', $email);
mysql查询中出现错误:-
SELECT * WHERE ` = 'muraddnw@gmail.com' LIMIT 1
您的代码尚未指定要从中查询的表。因此使用以下内容:-
$this->db->select('id');
$this->db->from('tablename');
$this->db->where('email', $email);
希望这能有所帮助。
不需要制作一个特殊的函数,这就足够了
$this->form_validation->set_rules(
'email', 'Email', 'trim|required|valid_email|is_unique'
);
使用is_unique[table.field]
添加表名和字段。
$this->form_validation->set_rules(
'email', 'Email', 'trim|required|valid_email|is_unique[table.field]|callback_isEmailExist'
);
您可以使用form_validator函数is_unique[table_name.field_name]