How can the affectedRows function be utilized to ensure the correct number of records are updated in a database query?
When performing database queries that update records, it is important to verify that the correct number of records were affected by the query. This can be done using the affectedRows function provided by the database connection object. By checking the return value of affectedRows after executing the query, you can ensure that the expected number of records were updated.
// Perform an update query
$query = "UPDATE table_name SET column_name = 'new_value' WHERE condition";
$result = $connection->query($query);
// Check the number of affected rows
if ($connection->affectedRows() == 1) {
echo "Record updated successfully";
} else {
echo "Error updating record";
}