michaellunsford Posted May 15, 2006 Share Posted May 15, 2006 using PHP to generate a select box. Client wants the ability to change the order the items appear in the select box. Right now I must be going the long way around:[code]<?php $last_one = mysql_fetch_assoc(mysql_query("SELECT * FROM `table` ORDER BY `sort_by` DESC LIMIT 1"));mysql_query("INSERT INTO `table` (`name`,`value`,`sort_by`) VALUES ('$name','$value','".($last_one['sort_by']+1)."')");?>[/code]This works great, but I keep thinking there's a shorter way to do this. Is there a way to tell the insert query that I want the greatest value of `sort_by` + 1 without using a select query to find out what the last one is? Quote Link to comment https://forums.phpfreaks.com/topic/9722-manual-auto-increment-sort-of/ Share on other sites More sharing options...
fenway Posted May 16, 2006 Share Posted May 16, 2006 You have two options: use user variables or subqueries (4.1+).[code]SET @nextSortBy := SELECT MAX(sort_by) + 1 FROM `table`"INSERT INTO `table` (`name`,`value`,`sort_by`) VALUES ('$name','$value',@nextSortBy)"[/code]or:[code]"INSERT INTO `table` (`name`,`value`,`sort_by`) VALUES ('$name','$value', (SELECT MAX(sort_by) + 1 FROM `table` ) )"[/code]In either case, you should be using max() and just getting back a single value, rather than * on the whole table with an order by & limit.Hope that helps. Quote Link to comment https://forums.phpfreaks.com/topic/9722-manual-auto-increment-sort-of/#findComment-36241 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.