Handling a MySQL duplicate entry error (1062) in PHP without a crash
Duplicate entry 'jane@example.com' for key 'users.email'Short answer
MySQL error 1062 (SQLSTATE 23000) means an INSERT or UPDATE broke a unique or primary key. Since PHP 8.1 mysqli throws mysqli_sql_exception and PDO throws PDOException, so an uncaught one ends the script. Catch the exception, compare the error number with 1062, and show a friendly message or run an upsert.
Fix it fast
1Find out which cause you have
Find which unique key was hit. The message names the value and the key, and the error number is 1062 with SQLSTATE 23000. Print both from the exception.
<?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); try { $mysqli->query("INSERT INTO users (email) VALUES ('jane@example.com')"); } catch (mysqli_sql_exception $e) { echo $e->getCode(), ' ', $e->getSqlState(), ' ', $e->getMessage(); }2Match what you see, then jump to its fix
- 1
Fatal error: Uncaught mysqli_sql_exception: Duplicate entry ...mysqli throws and nothing catches itFix - 2
Fatal error: Uncaught PDOException on an INSERT that repeats a unique valuePDO throws a PDOException that is not caughtFix - 3
The same key is inserted on every import or page load, and the duplicate error is the expected caseThe row existing already is normal and should updateFix
- 1
What does the error look like?
Duplicate entry 'jane@example.com' for key 'users.email'Fatal error: Uncaught PDOException (duplicate entry, driver code 1062)Fatal error: Uncaught mysqli_sql_exception: Duplicate entry
Cause 1 of 3
mysqli throws and nothing catches it
1Check
From PHP 8.1 the default mysqli mode is MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT, which throws mysqli_sql_exception instead of returning false. If your code only tests the return value of query(), the exception skips that test.
php -r 'mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); echo "strict";'2Fix
Wrap the write in try/catch. For mysqli, getCode() holds the MySQL error number, so test it against 1062 and rethrow anything else.
<?php
try {
$stmt = $mysqli->prepare("INSERT INTO users (email) VALUES (?)");
$stmt->bind_param("s", $email);
$stmt->execute();
} catch (mysqli_sql_exception $e) {
if ($e->getCode() === 1062) {
echo "That email is already registered.";
} else {
throw $e;
}
}3Verify
Submit the same email twice. The second attempt prints the friendly message and the script keeps running.
php register.php jane@example.com && php register.php jane@example.comConfirmed by php.net
Cause 2 of 3
PDO throws a PDOException that is not caught
1Check
PDO uses exception mode by default from PHP 8.0. The exception carries an errorInfo array that matches PDO::errorInfo(): element 0 is the SQLSTATE and element 1 is the driver error code, which is 1062 for MySQL duplicates.
grep -n "ATTR_ERRMODE\|new PDO" db.php2Fix
Catch PDOException and read errorInfo[1]. Send other errors up unchanged.
<?php
try {
$stmt = $pdo->prepare("INSERT INTO users (email) VALUES (:email)");
$stmt->execute([':email' => $email]);
} catch (PDOException $e) {
if (($e->errorInfo[1] ?? null) === 1062) {
echo "That email is already registered.";
} else {
throw $e;
}
}3Verify
Run the insert twice with the same value. Only the second run takes the 1062 branch.
php register.phpConfirmed by php.net
Cause 3 of 3
The row existing already is normal and should update
1Check
If a repeat insert should refresh the stored row, an error is the wrong tool. MySQL can update the existing row in the same statement when a unique index or primary key would be duplicated.
mysql -e "SHOW CREATE TABLE users\G" mydb2Fix
Use INSERT ... ON DUPLICATE KEY UPDATE with a row alias. The older VALUES(col) form still works but the manual marks it deprecated. With several unique keys the matched row can be ambiguous, so use it on a table with one.
INSERT INTO users (email, name) VALUES ('jane@example.com', 'Jane') AS new
ON DUPLICATE KEY UPDATE name = new.name;3Verify
Run it twice. The second run changes the existing row and reports 2 affected rows when a value changed, or 0 when nothing changed.
mysql -e "SELECT email, name FROM users WHERE email = 'jane@example.com'" mydbConfirmed by dev.mysql.com
How do I stop it coming back?
- Put the unique index in the database; do not rely on a SELECT before the INSERT, because two requests can pass that check together.
- Catch only the error number you expect and rethrow the rest, so other failures are not swallowed.
- Never echo the raw exception message to visitors: it contains the stored value.
- Use an upsert for data that is meant to be re-imported.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- ShopGoAn e-commerce aggregator with a Python scraping engine behind its catalog, past 10K Google Play downloads.
Related fixes
Databases
Error 1062 on a composite primary key when the row looks new
ERROR 1062 (23000): Duplicate entry 'x' for key 'orders.uq_email'
A composite primary key is unique only for the whole column combination, so a 1062 means some unique index saw an equal value.
3 causes, each with a fixBack end
CodeIgniter 4: try/catch does not catch a failed insert in the model
DatabaseException
CodeIgniter throws a DatabaseException on a failed query only when DBDebug is true, and inside a transaction it does not throw unless you ask.
3 causes, each with a fixBack end
CodeIgniter 4 where() builds a different condition than you meant
A SQL syntax error that appears only when a value contains a quote character
The query builder joins every where() with AND and every orWhere() with OR, with no brackets.
3 causes, each with a fixBack end
Call to undefined function mysql_pconnect() after a PHP upgrade
Call to undefined function mysql_connect()
The old mysql_* functions belonged to the ext/mysql extension, which PHP removed in version 7.0.
2 causes, each with a fixBack end
CodeIgniter cannot connect to the MySQL database server
Unable to connect to your database server using the provided settings.
CodeIgniter only reports that its connection failed.
4 causes, each with a fixBack end
Laravel insert fails with 'Field user_id doesn't have a default value'
The insert works when the column is removed or made nullable
Error 1364 means Laravel sent an INSERT without a value for a NOT NULL column that has no default, and MySQL strict mode refuses it.
3 causes, each with a fix