howtos » PHP code snippet - Reorder items in a table

PHP code snippet - Reorder items in a table

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:
  1. function moveItem ($n_steps) {
  2. if ($n_steps == 0) {
  3. return;
  4. }
  5.  
  6. $cur_pos = $this->pos;
  7. $new_pos = $cur_pos + $n_steps;
  8.  
  9. if ($n_steps <0) {
  10. $min_pos = $cur_pos + $n_steps;
  11. $max_pos = $cur_pos - 1;
  12. $shift_sign = '+';
  13. } elseif ($n_steps> 0) {
  14. $min_pos = $cur_pos + 1;
  15. $max_pos = $cur_pos + $n_steps;
  16. $shift_sign = '-';
  17. } else {
  18. return;
  19. }
  20.  
  21. $id = $this->id;
  22.  
  23. //Reorder existing items that will be existed by moving this item
  24. $sql = "UPDATE  positions
  25. SET  order_num = order_num $shift_sign 1
  26. WHERE   id = $id
  27. AND position>= $min_pos
  28. AND position <= $max_pos";
  29.  
  30. $this->db->query($sql);
  31.  
  32. //Now set new position for this item
  33. $sql = "UPDATE postions SET position = $new_pos WHERE id = $id";
  34. $this->db->query($sql);
  35. }

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <blockquote cite=""> <code> <em> <strong>