I have a database with the following table:
CATEGORY
id
name
Another entity in the database can be assigned any of these categories through a foreign key on that entity. In my PHP application, I want a dropdown option select box to show the current category by default, but also allow any of the others to be selected in order to change the category that the entity belongs to.
In trying to formulate a SQL query to populate the dropdown select options that shows all the categories starting with the currently selected one, I was trying different things and came up with this:
SELECT name FROM category ORDER BY id=[ID] DESC
Which seems to work properly given my small set of sample data, but seeing as I was just guessing around, I’m not 100% confident this is the proper query and will continue to work with the full dataset. I’m hoping someone can confirm that this SQL is appropriate, or suggest if there is a better way to accomplish this.
Also, the form action links to a page that contains the UPDATE query, and currently I am getting the category ID back by first running a SELECT query for the category name, but is there a way I can just assign the category ID for each category to it’s respective select option?
Thanks!
I’m not sure your best option is re-ordering the select instead of simply making the particular option selected (example below).
Your query should work consistently because id=[id] is a boolean which will then be converted to a 0 or a 1 depending on whether it is true or false. I do wonder about the index in such cases — MySQL will not be likely to compensate for that. You may wish to swap that with a
UNION DISTINCT, but you’ll have to benchmark yourself:As to getting the ID from the
<select>directly, you can always use the value property of the options:In the above, if green is selected, PHP will receive
$_REQUEST['mySelecte'] == '1'.FINAL PHP EXAMPLE