Jump to content

manual auto-increment (sort of)


michaellunsford

Recommended Posts

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?
Link to comment
Share on other sites

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.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.