Two simple scenarios:
$group_sql = $db->prepare("UPDATE `groups` SET `group`=? WHERE `group_id`=?;");
foreach($_POST['groups'] as $id => $group)
{
$group_sql->execute(array($group, $id));
}
And multi-update:
$query = array();
foreach($_POST['groups'] as $id => $group)
{
$query[] = "WHEN {$id} THEN {$db->quote($group)}";
}
$query = "
UPDATE `groups`
SET `group` = CASE `group_id`
" . implode("\r\n", $query) . "
END
WHERE `group_id` IN (" . implode(',', array_keys($_POST['groups'])) . ");
";
Which will eventually generate:
UPDATE `groups`
SET `group` = CASE `group_id`
WHEN 3054 THEN 'moteris savo vaikams'
WHEN 3055 THEN 'bičių šeimoje'
END
WHERE `group_id` IN (3054,3055)
Which one is better to use?
UPDATE
Since I noticed that people are not familiar with such method, I’ve decided to expand the example to use multiple column/row update.
UPDATE `groups`
SET `group` = CASE `group_id`
WHEN 3054 THEN 'moteris savo vaikams'
WHEN 3055 THEN 'bičių šeimoje'
END,
SET `description` = CASE `group_id`
WHEN 3054 THEN 'foo'
WHEN 3055 THEN 'bar'
END
WHERE `group_id` IN (3054,3055)
It depends entirely on your table and index structure. If
group_idis index so that it can look it up directly, without scanning an index or a table it should yield similar performance.If it isn’t indexed the last form should be able to handle with one index/table scan instead of two, which will get better performance.
Interesting idea to handle multiupdates that way, haven’t seen it before.