What are some best practices for handling unique constraint violations in PHP when working with databases?

When working with databases in PHP, unique constraint violations can occur when trying to insert or update a record that would violate a unique constraint, such as a duplicate key. To handle these violations gracefully, you can catch the exception thrown by the database and handle it accordingly, such as displaying a user-friendly error message or logging the issue for further investigation.

try {
    // Attempt to insert or update record
} catch (\PDOException $e) {
    if ($e->errorInfo[1] == 1062) { // MySQL error code for duplicate entry
        // Handle unique constraint violation
        echo "Error: Record already exists.";
    } else {
        // Handle other database errors
        echo "Error: " . $e->getMessage();
    }
}