I have a table with say 20 rows each with a number for display order (1-20).
SELECT * FROM `mytable` ORDER BY `display_order` DESC;
From an adm
This is a great way of sorting items on a database. Exactly what i was looking for ;)
Here's an improved version of Jamon Holmgren's version. This function is totally dynamic:
function reOrderRows($tablename, $ordercol, $idsarray){
$query = "UPDATE $tablename SET $ordercol = (CASE $ordercol ";
foreach($idsarray as $prev => $new) {
$query .= " WHEN $prev THEN $new\n";
}
$query .= " END) WHERE $ordercol IN (" . implode(",", array_keys($idsarray)) . ")";
mysql_query($query);
}
This assumes that you have a column $ordercol on your table $tablename just for ordering purposes.
The $idsarray is an array in the format array("current_order_num" => "updated_order_num").
So if you just want to swap two lines in your table (imagine that you have for example a "move up" and "move down" icons on your webpage), you can use this function on top of the previous one:
function swapRows($tablename, $ordercol, $firstid, $secondid){
$swaparray = array("$firstid" => "$secondid", "$secondid" => "$firstid");
reOrderRows($tablename, $ordercol, $swaparray);
}