我是PHP的新手,正在努力用此代码添加重复的电子邮件支票
在将信息推送到mysql数据库方面,这是我需要的,但是我希望它不允许重复的电子邮件。我正在寻找为与输入的电子邮件匹配的结果添加计数,然后如果> 1标记为重复的标记。老实说,我不确定这应该在流程中去哪儿或如何去做。任何帮助将不胜感激。
<?php
//if form has been submitted process it
if(isset($_POST['submit'])){
//collect form data
extract($_POST);
if(!isset($error)){
try {
//insert into database
$stmt = $db->prepare('INSERT INTO email_subs (email) VALUES (:email)') ;
$stmt->execute(array(
':email' => $email
));
//redirect to index page
header('Location: ./thanks.php?action=added');
exit;
} catch(PDOException $e) {
echo $e->getMessage();
}
}
}
//check for any errors
if(isset($error)){
foreach($error as $error){
echo '<p class="error">'.$error.'</p>';
}
}
?>
<form action='' method='post'>
<input type='email' name='email' required="required" data-error="Valid email is required." value='<?php if(isset($error)){ echo $_POST['email'];}?>'></p>
<div class="invalid-feedback">
Please enter your email.
</div>
<button type='submit' name='submit' value='Submit' class="btn-red">Sign-Up</button>
</form>
答案 0 :(得分:1)
首先将email
列设置为数据库表中的唯一键
然后检查您的PDOException
try {
$prep->execute($values);
// do other things if successfully inserted
} catch (PDOException $e) {
if ($e->errorInfo[1] == 1062) {
$email_error = "Email already exists in our mailing list"
// then show this in html
} else {
}
}