A SELECT that checks whether an email already exists can improve the form response, but it cannot enforce uniqueness. Two requests can both pass the check before either inserts. Put a unique constraint on the stored email key and treat the insert as the final decision.
Last updated: November 23, 2026.
<?php
$statement = $pdo->prepare(
'INSERT INTO users (email, password_hash) VALUES (:email, :hash)'
);
try {
$statement->execute([
'email' => $normalizedEmail,
'hash' => password_hash($password, PASSWORD_DEFAULT),
]);
} catch (PDOException $exception) {
$mysqlError = $exception->errorInfo[1] ?? null;
if ($exception->getCode() === '23000' && $mysqlError === 1062) {
throw new DomainException('That account cannot be created.');
}
throw $exception;
}Before using this insert, add a database constraint such as ALTER TABLE users ADD CONSTRAINT uq_users_email UNIQUE (email). Name the constraint clearly, and preserve the original exception for every failure that is not the expected duplicate-key case.
Let the database close the race window
A unique index makes the rule atomic even when requests arrive together or another importer writes to the table. MySQL documents unique indexes as rejecting duplicate indexed values. Its error reference identifies duplicate entry error 1062 with SQLSTATE 23000.
You may still perform a pre-check to show feedback before hashing a password, but keep the exception path because the database state can change after that check. Do not use INSERT IGNORE for registration: it can turn important data errors into warnings and makes it harder to know whether an account was created.
Define what “same email” means once
Normalize input according to a documented application policy before both lookup and insert. At minimum, trim surrounding whitespace and validate the address. Decide whether case differences should compare equal, then choose a column collation or a separate normalized key that implements that decision consistently. Do not apply ad hoc transformations in only one endpoint.
Return a controlled response after a duplicate. A registration form may offer sign-in or password recovery, but a sensitive application should avoid confirming whether a particular address has an account. The prepared statement protects values from SQL injection; password_hash() creates the password hash independently of the email rule. Log unexpected database failures internally and rethrow them rather than mislabeling every integrity error as a duplicate email.