我有一個連接到我的數據庫的測驗表單,但是我需要防止插入重複的電子郵件條目。 我曾嘗試以下:檢查數據庫中是否已存在電子郵件
//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