Skip to content Skip to sidebar Skip to footer

How To Change Order Of Rows In Table Based On List Of Rows Id?

I have table with id test_table
and or has different id. I have ordered list of rows' id like ['name','value','description'] what is

Solution 1:

I think you are after a client side table sorting, there's quite a few available online, it depends what javascript library you are familiar with. I have chosen to use a jQuery plugin called tablesorter and I am assuming based on your tags that it might be a good option for you too.

The downside to it is that it is client-side only, so If a user doesn't have Javascript enabled, they will not be able to sort the table, I'd say that is not a major problem, the average user always have Javascript enabled.

The other option is to build a server-side sorting, this can be as easy as adding

ORDER BY "$selectedField" "$order"

in your database query. It will also ensures that it works without Javascript.

Nowadays many of the popular web development frameworks provide that sort of feature, if you haven't discovered it yet, I encourage you to take a look at some options for your programming language.


Solution 2:

If you are wanting to do everything in jQuery, which it looks like you are trying to do, then I would look into jQuery Sortable but if you want it to be like a link/button that sorts each field by say Ascending or Descending order, or by like usernames etc, and keep it server-side then what I would suggest is have the button/link reload itself with a sub-query in the url that would say something like ?order_by=asc or ?order_by=username&dir=asc then run a check for it on the page, passing that variable/sub-query ($_GET['order_by']) to a function. In the function, do a query that looks similar to this:

$order_by = "ORDER BY " . $_GET['order_by'] . $_GET['dir'];
$query = "SELECT *
          FROM table
          $order_by";

You could then use this same query for the main page load (that hasn't been sorted) without difficulty using the variable, then when the query is re-run with a loaded $order_by then the list will be ordered by parameter.


Post a Comment for "How To Change Order Of Rows In Table Based On List Of Rows Id?"