This snippet of code reorders items in a table based on the number of steps you want to move an item from its current position. It moves the item of interest to its new position and shifts all other items to their new shifted positions.
PHP:
-
function moveItem ($n_steps) {
-
if ($n_steps == 0) {
-
return;
-
}
-
-
$cur_pos = $this->pos;
-
$new_pos = $cur_pos + $n_steps;
-
-
if ($n_steps <0) {
-
$min_pos = $cur_pos + $n_steps;
-
$max_pos = $cur_pos - 1;
-
$shift_sign = '+';
-
} elseif ($n_steps> 0) {
-
$min_pos = $cur_pos + 1;
-
$max_pos = $cur_pos + $n_steps;
-
$shift_sign = '-';
-
} else {
-
return;
-
}
-
-
$id = $this->id;
-
-
//Reorder existing items that will be existed by moving this item
-
$sql = "UPDATE positions
-
SET order_num = order_num $shift_sign 1
-
WHERE id = $id
-
AND position>= $min_pos
-
AND position <= $max_pos";
-
-
$this->db->query($sql);
-
-
//Now set new position for this item
-
$sql = "UPDATE postions SET position = $new_pos WHERE id = $id";
-
$this->db->query($sql);
-
}