我有一个连接到数据库的测验表单,但是我需要防止插入重复的电子邮件条目。 我尝试过以下方法:
//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;
}
}
最佳答案
两个问题:
- 您从未调用
checkEmail()
函数,因此它永远不会运行。您应该从函数中删除该代码,或者只在需要运行的地方调用该函数。 - 在该函数中,您将检查是否存在字面上等于“$email”的电子邮件。 PHP 只会解析双引号中的变量 - 更改该行以使用
where('email','=',"$email")
代替。
关于php - 检查数据库中是否已存在电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22758323/