本文介绍了检查数据库中是否已存在电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个连接到数据库的测验表单,但是我需要防止插入重复的电子邮件条目。
我尝试了以下操作:
I have a quiz form that is connected to my database, however I need to prevent duplicate email entries being inserted.I have tried the following:
//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
}
但结束条目,这是我的所有代码(可能是我未在正确的位置运行它?)
But I 'm still getting duplicate entries, here is all my code (may be I'm not running this in the correct place?)
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;
}
}
推荐答案
两个问题:
- 您永远不会调用
checkEmail()
函数,因此永远不会运行。您应该从函数中删除该代码,或者仅在需要运行该函数的地方调用该函数。 - 在该函数中,您正在检查是否存在不等于 $ email的电子邮件。 PHP仅会解析双引号中的变量-更改该行以使用
where('email','=', $ email)
代替。
- You're never calling your
checkEmail()
function so it's never running. You should either remove that code from the function or just call the function where it needs to run. - In that function you're checking that no email exists that literally equals "$email". PHP will only parse variables in double quotes - change that line to use
where('email','=',"$email")
instead.
这篇关于检查数据库中是否已存在电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!