我有一个连接到我的数据库的测验表单,但是我需要防止插入重复的电子邮件条目。 我曾尝试以下:检查数据库中是否已存在电子邮件
//Check for duplicate email addresses
function checkEmail($email){
$sql = DB::select('email')->from('myquiz')->where('email','=','$email')->execute();
$result = mysql_result(mysql_query($sql),0) ;
if($result > 0){
die("There is already a user with that email!") ;
}//end if
}
但我仍然得到重复的条目,这是我所有代码(可能是我没有在正确的位置上运行吗?)
public function action_myquiz() {
$this->template->styles['assets/css/myquiz.css'] = 'screen';
$this->template->jscripts[] = 'assets/scripts/myquiz.js';
$this->template->content = View::factory('quiz/myquiz');
$this->template->content->thanks = false;
if ($this->request->post('entry')) {
$post = $this->request->post('entry');
//Check for duplicate email addresses
function checkEmail($email){
$sql = DB::select('email')->from('myquiz')->where('email','=','$email')->execute();
$result = mysql_result(mysql_query($sql),0) ;
if($result > 0){
die("There is already a user with that email!") ;
}//end if
}
// save participant's info
$stmt = DB::query(Database::INSERT, 'INSERT INTO `myquiz` (`first_name`, `last_name`, `email`, `confirm_email`)
VALUES (:first_name, :last_name, :email, :confirm_email)');
$stmt->param(':first_name', $post['first_name']);
$stmt->param(':last_name', $post['last_name']);
$stmt->param(':email', $post['email']);
$stmt->param(':confirm_email', $post['confirm_email']);
try {
$stmt->execute();
// var_dump($post);
} catch (Exception $e) {
FB::error($e);
}
$this->template->content->thanks = true;
}
}
而不是检查电子邮件是否存在之前插入我会建议尝试添加一个try/catch块。捕获重复的关键异常,然后指出该电子邮件是重复的。 – Raj
或使电子邮件字段UNIQUE,然后尝试赶上像拉吉说 –
也确保你用双引号包装变量''$ email''应该是'''$ email'“'或只是'$ email'。你不能在单引号内解析变量 – mic