Reputation: 110
I'm very new to PHP and struggling with adding in duplicate email check with this code
This works as I need in terms of pushing info to mysql db but I want it to not allow duplicate emails. I was looking at adding a count for the results which match the inputted email and then if >1 flag as duplicate. I'm not sure where this should go in the flow or how to do it to be honest. Any help is greatly appreciated.
<?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>
Upvotes: 2
Views: 88
Reputation: 3094
At first set the email
column as a unique key in the db table
Then Check your 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 {
}
}
Upvotes: 1