I for one would never tell a person that an email is in use. I would just say that there’s something wrong and if the problem persist send an email at such and such address or something like that.
That only prevents if two people are just so happening to be entering the same email at the same time. If that is happening then there is something funny going on.
A better way to do that in my opinon would to do something like the following:
$query = "SELECT 1 FROM users WHERE email = :email";
$stmt = $pdo->prepare($query);
$stmt->bindParam(':email', $email);
$stmt->execute();
$row = $stmt->fetch();
return $row; // If it finds an email address it will be true:
I thought the UNIQUE KEY (email) would prevent the same email from being used more than once. Wouldn’t that prevent 2 people from entering the same email no matter when?
Your code is a little confusing to me as I thought id be inserting a row and not selecting one (can you explain it a little more?
Thanks…,.
I think that code is intended to run first - first check if the email is already in use, if it us, then handle that situation. By the time your insert query runs, you already know the email doesn’t exist in the table.
You should re-throw this exception instead of echoing it out.
} catch(PDOException $e) {
if ($e->getCode() == '23000') {
//is this the code I get if the email field is a DUPLICATE?
echo 'That email is in use';
} else {
throw $e;
}
}
As of the code, it varies, as far as I know. So there is another way - to use INSERT IGNORE and then check affected rows