How can the REPLACE INTO statement be modified to ensure that the correct row is updated when multiple rows match the condition?
When using the REPLACE INTO statement in MySQL, it will replace a row if a unique or primary key constraint is violated. To ensure that the correct row is updated when multiple rows match the condition, you can add a WHERE clause to specify additional conditions that uniquely identify the row to be updated. Example PHP code snippet:
<?php
// Assuming $conn is the MySQL connection object
$id = 1;
$name = "John Doe";
$age = 30;
$sql = "REPLACE INTO users (id, name, age) VALUES ($id, '$name', $age) WHERE id = $id";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>