front
id | cat_id | order 33 | 1 | 1 34 | 1 | 2
after
id | cat_id | order 33 | 1 | 2 34 | 1 | 1
Now using 4 queries
$ db is a $ mysqli wrapper for using a protective shell and injection protection
get the first record by id
$curr = $db->q('SELECT id,order,cat_id FROM `tbl` WHERE id`=? FOR UPDATE', 33)->fetch_assoc();
if the first record exists, find the next record in the order field
if($curr){ $next = $db->q('SELECT id,order FROM `tbl` WHERE `cat_id`=? AND `order`>? ORDER BY `order` LIMIT 1 FOR UPDATE', $curr['cat_id'],$curr['order']));
if the first and second value of the order of changing the order of replacement
if($prev['id']){ $db->q("UPDATE `tbl` SET `order`=? WHERE `id`=?",$next['order'],$curr['id']); $db->q("UPDATE `tbl` SET `order`=? WHERE `id`=?",$curr['order'],$next['id']); } }
Attention! Check for two records, lock rows for updates
source share