i have a table named member_photos
that stores member_id
, photo_id
, photo_dir
and photo_name
, when someone edited his photos, it posts an array containts info about photos, posted page has an array with photo informations but my problem is i use foreach loop and update every photo one by one like
UPDATE member_photos
SET photo_name = '$newphotoname'
WHERE photo_id = '$photoid'
that works but when this guy has 20 photos, array has 20 items so loop will do 20 queries. Is there any way that i can update all photos with single query?
UPDATE categories
SET display_order = CASE id
WHEN 1 THEN 3
WHEN 2 THEN 4
WHEN 3 THEN 5
END,
title = CASE id
WHEN 1 THEN 'New Title 1'
WHEN 2 THEN 'New Title 2'
WHEN 3 THEN 'New Title 3'
END
WHERE id IN (1,2,3)
in PHP
// An array containing the category ids as keys and the new positions as values
$display_order = array(
1 => 4,
2 => 1,
3 => 2,
4 => 3,
5 => 9,
6 => 5,
7 => 8,
8 => 9
);
$ids = implode(',', array_keys($display_order));
$sql = "UPDATE categories SET display_order = CASE id ";
foreach ($display_order as $id => $ordinal) {
$sql .= sprintf("WHEN %d THEN %d ", $id, $ordinal);
}
$sql .= "END WHERE id IN ($ids)";
echo $sql;
the resource for this info: http://www.karlrixon.co.uk/writing/update-multiple-rows-with-different-values-and-a-single-sql-query/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.