What are the best practices for handling duplicate entries in a MySQL database using PHP?

When handling duplicate entries in a MySQL database using PHP, one common approach is to use the ON DUPLICATE KEY UPDATE clause in your SQL query. This allows you to insert a new record if it doesn't already exist, or update the existing record if it does. Another approach is to check for duplicates before inserting data into the database to avoid duplication.

// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check for duplicates before inserting data
$query = "SELECT * FROM table_name WHERE column_name = 'value'";
$result = $mysqli->query($query);

if($result->num_rows == 0) {
    // Insert new record if no duplicates found
    $insert_query = "INSERT INTO table_name (column_name) VALUES ('value')";
    $mysqli->query($insert_query);
} else {
    // Handle duplicate entry
    echo "Duplicate entry found!";
}