How can duplicate entry errors be prevented and efficiently handled when inserting data into MySQL tables using PHP scripts?

Duplicate entry errors can be prevented and efficiently handled by using the ON DUPLICATE KEY UPDATE clause in MySQL when inserting data. This clause allows you to update the existing row if a duplicate entry is encountered, rather than throwing an error. By using this clause in conjunction with proper error handling in your PHP script, you can ensure that duplicate entries are either updated or ignored without disrupting the execution of your script.

<?php
// Establish a connection to the MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check for connection errors
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Prepare the SQL query with the ON DUPLICATE KEY UPDATE clause
$sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2') 
        ON DUPLICATE KEY UPDATE column2 = 'value2'";

// Execute the query
if ($mysqli->query($sql) === TRUE) {
    echo "Data inserted successfully";
} else {
    echo "Error: " . $sql . "<br>" . $mysqli->error;
}

// Close the database connection
$mysqli->close();
?>