JQuery Sortables with PHP and MySQL

This article will show you how to order a server-side list of fruit from a database using drag and drop behavior and then save them back to the database in order.

I recently worked on a project which required an unordered list to be re-ordered and then saved. I wasn't about to make users enter numbers next to each item so I looked toward JQuery's UI library.

Objective: We will display a list of fruit. The user can then drag the fruit and click a button to save the new order in the database.

For this example, let's use a database table named fruit with the following fields: id, name, weight.

Schema:

  1. CREATE TABLE fruit (
  2. id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  3. name VARCHAR(64) NOT NULL,
  4. weight TINYINT UNSIGNED NOT NULL
  5. ) TYPE = MYISAM ;
  6.  
  7. INSERT INTO fruit (name, weight) VALUES ('apple', 1);
  8. INSERT INTO fruit (name, weight) VALUES ('pear', 2);
  9. INSERT INTO fruit (name, weight) VALUES ('orange', 3);

I'll begin with some very basic PHP to setup the scenario.

This code queries the table ordered by weight. It then loops through and prints the result between list tags.

  1. <ul id="fruit_list">
  2.  
  3. <?php // query fruit table and print out each item
  4. $result = mysql_query("SELECT id, name, weight FROM fruit ORDER BY weight");
  5.  
  6. // print the list items
  7. while ($row = mysql_fetch_assoc($result)) {
  8. echo "<li>". $row['name'] ."</li>\n";
  9. }
  10. ?>
  11.  
  12. </ul>

We're printing a list of fruit from the database ordered by weight. Now how do we re-order the list of fruit? Simple, JQuery Sortables.

JQuery isn't going to do everything automatically. We still need to setup the form with input fields to submit the data. Let's take the last code block and add in hidden form elements which contain the value of each fruit ID.

  1. <form method="POST" action="<?php echo $_SERVER['PHP_SELF']?>">
  2.  
  3. <ul id="fruit_list">
  4. <?php // query fruit table and print out each item
  5. $result = mysql_query("SELECT id, name, weight FROM fruit ORDER BY weight");
  6.  
  7. // print the list items
  8. while ($row = mysql_fetch_assoc($result)) {
  9. echo '<li>
  10. <input type="hidden" name="fruit[]" value="'. $row['id'] .'" />
  11. '. $row['name'] .'</li>';
  12. }
  13. ?>
  14. </ul>
  15.  
  16. </form>

Notice we used fruit[] as the field name for all the rows. When the form is submitted,l the fruit ids will be put into a PHP array in the order they appear on the form. i.e. $_POST['fruit']. Since PHP already handles that for us, we just need a way to move the list items around.

You will need to download both JQuery and the JQuery UI. (yes, they are separate)

You can download the full package, but for sortables, you only need these components: UI Core, Draggable, and Sortable.

Let's finish our script by adding the JQuery and some PHP to handle the sort and update the database.

Full Script (tested)

  1. <?php
  2. // make your db connection up here ...
  3. $link = mysql_connect('localhost', 'user', 'pass');
  4. $db = mysql_select_db('dbname', $link);
  5.  
  6. // handle POST
  7. if ($_POST) {
  8. // use $i to increment the weight
  9. $i=1;
  10. // loop through post array in the order it was submitted
  11. foreach ($_POST['fruit'] as $fruit_id) {
  12. // update the row
  13. $result = mysql_query("UPDATE fruit SET weight=". $i . " WHERE id=". mysql_real_escape_string($fruit_id));
  14. // increment weight to make the next fruit heavier
  15. $i++;
  16. }
  17. }
  18. ?>
  19. <script type="text/javascript" src="jquery-1.2.6.js"></script>
  20. <script type="text/javascript" src="jquery-ui-1.5.1.min.js"></script>
  21. <script type="text/javascript">
  22. // when the entire document has loaded, run the code inside this function
  23. $(document).ready(function(){
  24. // Wow! .. One line of code to make the unordered list drag/sortable!
  25. $('#fruit_list').sortable();
  26. });
  27. </script>
  28. <form method="POST" action="<?php echo $_SERVER['PHP_SELF']?>">
  29.  
  30. <ul id="fruit_list">
  31. <?php // query fruit table and print out each item
  32. $result = mysql_query("SELECT id, name, weight FROM fruit ORDER BY weight");
  33.  
  34. // print the list items
  35. while ($row = mysql_fetch_assoc($result)) {
  36. echo '<li>
  37. <input type="hidden" name="fruit[]" value="'. $row['id'] .'" />
  38. '. $row['name'] .'</li>';
  39. }
  40. ?>
  41. </ul>
  42.  
  43. <input type="submit" name="reorder" value="Re-Order Fruit" />
  44.  
  45. </form>

And there we have it. Now when you submit the form, it should re-sort your fruit, update the db, and the fruit list should be displayed in the new order after submission.

Be sure to take a look at the JQuery Sortables documentation to see how much you can customize the behavior of the sort. With that and a little CSS, you can make this UI pretty sharp.

I believe I tested that code

I believe I tested that code when I wrote this. There's quite a few elements to this article, so maybe you could provide more info as to which part you're having a hard time with.

I can't get this to work.

I can't get this to work. Could you provide a working demo?
Thanks

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <img> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <h3> <h4> <h5> <h6> <h7>
  • Lines and paragraphs break automatically.
  • Images can be added to this post.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.