What are some best practices for handling unique constraints and avoiding duplicate entries in PHP MySQL operations?

When working with PHP and MySQL, it is important to handle unique constraints properly to avoid duplicate entries in the database. One way to do this is by using the "ON DUPLICATE KEY UPDATE" clause in MySQL queries. This clause allows you to update the existing record if a duplicate entry is found, instead of inserting a new one. By using this approach, you can ensure data integrity and prevent duplicate entries in your database.

// Example of handling unique constraints and avoiding duplicate entries in PHP MySQL operations

// Assuming $conn is your MySQL database connection

$name = "John Doe";
$email = "johndoe@example.com";

$query = "INSERT INTO users (name, email) VALUES ('$name', '$email') ON DUPLICATE KEY UPDATE name='$name', email='$email'";

if(mysqli_query($conn, $query)) {
    echo "Record inserted successfully or updated if duplicate entry found.";
} else {
    echo "Error: " . $query . "<br>" . mysqli_error($conn);
}