I have a PHP page that is interacting with a MYSQL database using PDO. I have a function that updates numerous fields in the database as requested. Since I do not know how many fields will be updated in advance, it is tricky to write a single query. Which of these methods is preferable (or is there another better way I do not know about)?
Query Building
$query = "UPDATE users SET ";
foreach ($changes as $field => $new_value)
{
$valid_field = validate_field($field);
$query .= "${valid_field} = :${valid_field} ";
}
$query = "WHERE id = :id ;";
// Prepare statement, bind values, execute, check for errors, etc
From what I have heard, this is not preferable. I tend to agree; this looks kinda ugly.
Transaction
$pdo_object->beginTransaction();
foreach ($changes as $field => $new_value)
{
$valid_field = validate_field($field);
$query = "UPDATE users SET ${valid_field} = :${valid_field} WHERE id = :id";
// Prepare statement, bind values, execute, check for errors, etc
}
$pdo_object->commit();
This seems safer to me, but the way it is written it looks like it searches the table for the row with that ID many times rather than just once like the other query.
Is the Query Building method faster than the Transaction method? Should the Transaction method be used despite slower speed for safety/security reasons?