Updating display order of multiple MySQL rows in one or very few queries

前端 未结 11 1247
迷失自我
迷失自我 2021-02-01 07:43

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

11条回答
  •  暖寄归人
    2021-02-01 07:53

    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); 
    }
    

提交回复
热议问题