How can the use of ON DUPLICATE KEY UPDATE in SQL queries help in avoiding duplicate entries in a database table?

When inserting data into a database table, using ON DUPLICATE KEY UPDATE in SQL queries can help avoid duplicate entries by updating the existing row if a duplicate key violation occurs. This means that instead of inserting a new row with the same key, the existing row will be updated with the new values.

<?php

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

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

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

// Insert or update data
$sql = "INSERT INTO table_name (key_column, value_column) VALUES ('key_value', 'new_value') 
        ON DUPLICATE KEY UPDATE value_column = 'new_value'";

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

$conn->close();

?>