I am a Junior PHP/MySQL Developer and need some help, how do I display front-end menu items by custom sorting using a text field through backend, I want to sort pages(Menut Title) by numbers like 1,2,3 …etc. in front end. It will be too better if I could understand dropdown menu sorting also from your answer. 😀 But anyway Here is my backend code but it is not working I think there needs an array which I am not understanding well:
<form name="sort_form" method="post" action="" >
<?php while($row = mysql_fetch_assoc($res)) { ?>
<tr>
<input type="hidden" value="<?php echo $row['id']; ?>" name="id" />
<td><input type="text" value="<?php echo $row['sort_by']; ?>" name="sort_by" size="2" maxlength="2"/></td>
<td><?php echo $row['page_title']; ?></td>
</tr>
<?php } ?>
<tr>
<td colspan="2" align="center"><input type="submit" name="submit" value="Sort" /></td>
</tr>
</form>
And here is the code for when action is performed.
<?php
if(isset($_POST['submit']) == "Sort") {
$id = intval($_POST['id']);
$sort_by = intval($_POST['sort_by']);
$query_update = "UPDATE `pages` SET `sort_by`='$sort_by' WHERE `id`='$id'";
$updated = mysql_query($query_update) or die ("Update failed!");
echo "Updated Successfuly!";
}
?>
Hope you understand!
Thanks
To sort the list you can not just update the sort_by field.
If your table has the following data
What would happend if you update row 3 with a sort_by value of 1? There will be two rows that have a sort_by value of 1, which one comes first? What happends if you again update row 2 with a sort_by value of 1… there can be a lot of collisions in the sort_by field.
However, there are several ways to get around this. One would be to simply swap sort_by values. So, when you update row 3 to a sort_by value of 1, you will also check if any sort_by values of 1 exists, and if they do, replace them with whatever row 3’s sort_by value is.
If swapping is not the behavior your looking for you can give the sort_by field a float data type. In this case everytime you insert or move something around in your table its sort_by field will be the average of the 2 rows it is sandwiched between. If you wanted to move row 3 between rows 1 & 2 you would set row 3’s sort_by value to 1.5.
Then if you wanted to move 2 back inbetween 1 and 3 you would set 2’s sort_by value to 1.25
you can continue to do this for a very long time. However, since you are editing your sort by field with a textfield this does not appear to be the right choice for you.
What I suggest is having another column in your table called “sort_by_updated_at”. Everytime you update your sort_by values set sort_by_updated_at to the current time. This way you can sort on two columns. You sort on your regular sort_by field but if there is any collisons you look at the sort_by_updated_at field and whichever row has a lower sort_by_updated_at value will precede all others.