I'm using php and mysql. I have a table with the id column set to auto increment as the primary key. I'm trying to add another column called sort_order. The sort_order column should auto increment when the row is inserted. Then a user will be able to change the sort_order value. But mysql does not allow auto increment for more than one column?
What is the best way to auto increment the sort_order value?
By popular Request, some more explanation.
In administration area, the user will have a list of categories. Using javascript the user can drag the order they want the categories in. The script then posts a list of all the ids in the new order, and the sort_order values in the old order.
I then have a php function which updates mysql with the new sort_order value.
All of this is already done, except I had manually filled out all the sort_order values. I want it to be able to have a value when a user creates a new category.
Then I can use the sort_order to display the category order correctly on the front end.
I have everything done already. But in development I manually filled in the values for the sort_order.
MySQL server already provides two auto increment variables: auto_increment_increment and auto_increment_offset, which can be used to generate different auto increment values on each member.
AUTO_INCREMENT / IDENTITY constraints can take between 0 and three arguments. These arguments let you specify the column's start value, how much it increments or decrements, and how many unique numbers each node caches per session.
But unfortunately there can be only one AUTO_INCREMENT column per table in MySQL. :-/ So this situation belongs to a class of problems known as MAX+1 problems.
MySQL has the AUTO_INCREMENT keyword to perform auto-increment. The starting value for AUTO_INCREMENT is 1, which is the default. It will get increment by 1 for each new record. To get the next auto increment id in MySQL, we can use the function last_insert_id() from MySQL or auto_increment with SELECT.
You can leave your sort column equal to NULL by default. The only thing you need is a little smarter query. For instance:
select *
from something
order by ifnull(sort, id)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With