In PHP, what is the recommended approach for handling duplicate entries in a database when inserting records?

When inserting records into a database in PHP, it is important to handle duplicate entries to prevent errors or data inconsistencies. One recommended approach is to use the "ON DUPLICATE KEY UPDATE" clause in an SQL query, which allows you to update the existing record if a duplicate entry is found. This way, you can avoid inserting duplicate records and ensure data integrity.

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

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

$sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2') 
        ON DUPLICATE KEY UPDATE column1 = 'value1', column2 = 'value2'";

if ($conn->query($sql) === TRUE) {
    echo "Record inserted successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>