What are the best practices for handling unique keys and updating existing records in a MySQL database using PHP?

When handling unique keys and updating existing records in a MySQL database using PHP, it is important to first check if the record already exists before attempting to insert a new one. If the record exists, you should update the existing record instead of inserting a duplicate. This can be achieved by using the ON DUPLICATE KEY UPDATE clause in your SQL query.

// Assuming $conn is your database connection

// Check if the record already exists
$query = "SELECT * FROM your_table WHERE unique_key = 'value'";
$result = mysqli_query($conn, $query);

if (mysqli_num_rows($result) > 0) {
    // Update existing record
    $updateQuery = "UPDATE your_table SET column1 = 'new_value' WHERE unique_key = 'value'";
    mysqli_query($conn, $updateQuery);
} else {
    // Insert new record
    $insertQuery = "INSERT INTO your_table (unique_key, column1) VALUES ('value', 'new_value')";
    mysqli_query($conn, $insertQuery);
}