【发布时间】:2014-05-10 14:24:15
【问题描述】:
我有一个连接到我的数据库的测验表格,但是我需要防止插入重复的电子邮件条目。 我尝试了以下方法:
//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 所说的那样捕获
-
还要确保将变量用双引号括起来
'$email'应该是"'$email'"或只是$email。您无法解析单引号内的变量 -
谢谢!我会选择 Raj 的选项,因为我认为这将是最好的 :)