How to handle error for duplicate entries?

How to handle error for duplicate entries?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Handling Duplicate Entry Errors in PHP and MySQL

When a primary key is derived from user input, the database enforces uniqueness strictly. If your application attempts to insert a record where that primary key already exists, MySQL throws an error like Duplicate entry 'entered value' for key 1. This raw error message often breaks the user experience immediately, halting the request and exposing internal database structure details to the client. The goal is to intercept this specific exception and present a friendly prompt asking the user to choose a different value.

The most robust way to handle this in PHP is to catch the PDOException that MySQL throws when a constraint violation occurs. You cannot simply suppress the error or rely on generic try-catch blocks without filtering for the specific type of exception. The PDO::ERRNO property provides the specific error code returned by the database server. For duplicate key violations, this code is consistently 1062.

Here is a pattern you can apply in your form submission handler:

try {
    $stmt = $pdo->prepare('INSERT INTO users (username) VALUES (:name)');
    $stmt->execute([':name' => $_POST['username']]);
} catch (PDOException $e) {
    if ($e->errorInfo[1] == 1062) {
        // Handle the duplicate key error gracefully
        echo "This username is already taken. Please choose a different one.";
    } else {
        // Log or handle other database errors appropriately
        logError($e); 
    }
}

In this example, we check $e->errorInfo[1]. The first element of the errorInfo array is the MySQL error code. If it matches 1062, you know definitively that a unique index was violated. This approach prevents you from catching unrelated errors like connection timeouts or syntax mistakes in SQL queries and treating them as duplicate entries.

There are alternative strategies depending on your architectural preferences. One common method is to use the INSERT ... ON DUPLICATE KEY UPDATE syntax. This statement attempts the insert, and if a duplicate key error occurs, it executes an update instead. However, this logic assumes you want to update existing data. If your business logic strictly requires creating new records and failing on duplicates, catching the exception is often clearer than trying to force an update that might not be desired.

Another consideration is database-level constraints versus application-level validation. Relying solely on ON DUPLICATE KEY UPDATE can sometimes mask data integrity issues if you don't explicitly handle the outcome. By catching the error in PHP, you retain full control over the user feedback loop. You can decide whether to redirect the user back to the form, display an inline message, or log the attempt for security auditing before rejecting the request.

If you are working within a Laravel application, the ecosystem provides specific ways to handle these scenarios without exposing raw database errors to the view. The Illuminate\Database\QueryException class wraps PDO exceptions, allowing you to access the error code similarly but with added context. You can configure your application to throw an exception automatically when a validation rule fails, then catch it in a controller or middleware to return a standardized response.

For more complex scenarios where you need to handle multiple constraints simultaneously, checking the error code remains the most precise method. Fabricating an API or package method does not exist for this specific issue; the solution lies in standard PHP exception handling and PDO configuration. Ensuring your application logs these events internally while providing a clean message externally is the best practice for maintaining both security and usability.

If you are looking for deeper guidance on managing database interactions within Laravel specifically, resources like https://laravelcompany.com offer practical examples on structuring error handling in modern PHP applications, though the core logic of checking error codes remains universal across frameworks.

Our network