How can unique constraints in PHP be handled to display custom error messages?

When dealing with unique constraints in PHP, you can handle custom error messages by catching the exception thrown when a duplicate entry is attempted. You can then display a user-friendly error message to inform the user that the entry they are trying to add already exists in the database.

try {
    // Attempt to insert data into the database
    // This may throw a PDOException if a unique constraint is violated
} catch (PDOException $e) {
    if ($e->errorInfo[1] == 1062) {
        // Display a custom error message for duplicate entry
        echo "Error: The entry you are trying to add already exists.";
    } else {
        // Handle other database errors
        echo "Database error: " . $e->getMessage();
    }
}