Altimus Prime
Altimus Prime

Reputation: 2327

How to manage an order_by column for dynamic ordering, mysql and php

I have a variable number of rows in a mysql table. I want to change the order they appear, irrespective of the content of any significant column, what's the best way to do it?

For example, if I have:

id , content, order-by
1  , d      , 1
2  , a      , 2
3  , v      , 3
4  , i      , 4
5  , d      , 5

and want to reorder the fields to:

id , content, order-by
3  , v      , 1
4  , i      , 2
5  , d      , 3
2  , a      , 4
1  , d      , 5

which sorted by id would look like:

id , content, order-by
1  , d      , 3
2  , a      , 4
3  , v      , 1
4  , i      , 2
5  , d      , 5

The complication is that I have to manually or programmatically update each other row affected by a change in order, deletion or addition. Isn't there some built in functionality or script someone already has done to save some time on this?

Thank you in advance for your time.

Upvotes: 0

Views: 1351

Answers (1)

janenz00
janenz00

Reputation: 3310

Whenever your program changes the order, you will have to update the order_by column with the correct order_by value. I had worked on a program with an assembly in which page orders can be changed by drag and drop. The positions will be held in JS variables, till time to save. On submit, the revised order will be updated in the table.

When you access the table you have to do :

 SELECT * from table order by order_by;

It all depends on the size of your table though, and what you are trying to achieve with the order.

As @Matt Gibson mentioned in the comment, if you are trying to implement a drag and drop ordering of a list, you can use jQuery UI Sortable . You can achieve something like -

 var result = $('#sortable').sortable('toArray');
 $.post(
        url,
        "order="+result
 );

Receive the position values in the PHP url, and process it.

Upvotes: 1

Related Questions