How can UNIQUE KEY Constraints in a database be utilized in PHP to ensure data integrity and prevent duplicate entries?

To ensure data integrity and prevent duplicate entries in a database, UNIQUE KEY constraints can be utilized in PHP. This constraint ensures that a specific column or a combination of columns must contain unique values, thus preventing duplicate entries from being inserted into the database.

// Create a table with a UNIQUE KEY constraint on a specific column
$sql = "CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) UNIQUE,
    email VARCHAR(100) UNIQUE
)";

// Insert data into the table, ensuring unique values for username and email
$sql = "INSERT INTO users (username, email) VALUES ('john_doe', 'john.doe@example.com')";