Hey, I have a table with “id”, “name”, and “weight” columns. Weight is an unsigned small int.
I have a page that displays items ordered by “weight ASC”. It’ll use drag-n-drop, and once the order is changed, will pass out a comma-separated string of ids (in the new order).
Let’s say there’s 10 items in that table. Here’s what I have so far:
Sample input:
5,6,2,9,10,4,8,1,3,7
Sample PHP handler (error handlers & security stuff excluded):
<?php
$weight = 0;
$id_array = explode(',', $id_string);
foreach ($id_array as $key => $val)
{
mysql_query("UPDATE tbl SET weight = '$weight' where id = '$val' LIMIT 1");
$weight++;
}
?>
When I make a change to column order, will my script need to make 10 separate UPDATE queries, or is there a better way?
You can only specify one
whereclause in a single query — which means, in your case, that you can only update one row at a time.With 10 items, I don’t know if I would go through that kind of troubles (it means re-writing some code — even if that’s not that hard), but, for more, a solution would be to :
deleteall the rowsinserts them all backThe nice point is that you can do several
inserts in a single query ; don’t know for 10 items, but for 25 or 50, it might be quite nice.Here is an example, from the insert page of the MySQL manual (quoting) :
Of course, you should probably not insert “too many” items in a single insert query — an insert per 50 items might be OK, though (to find the “right” number of items, you’ll have to benchmark, I suppose ^^ )