Last Updated: February 25, 2016
· lukaszwakula

Sortable gallery to database

Always wanted to create a sortable gallery and save its order in the database for Your users?
There You go.

We will use HTML for page structure, jQuery for AJAX request, PHP to fetch data and MySQL to insert data into our database. <br>
Some simple steps here and a link to a demo and also a download page.

HTML markup

<button class="save">Save order</button>        
<ul class="sortable">
  <li id='item-1'><img src="images/photos/1.jpg" alt=""></li>
  <li id='item-2'><img src="images/photos/2.jpg" alt=""></li>
  <li id='item-3'><img src="images/photos/3.jpg" alt=""></li>
  <li id='item-4'><img src="images/photos/4.jpg" alt=""></li>
  <li id='item-5'><img src="images/photos/5.jpg" alt=""></li>
  <li id='item-6'><img src="images/photos/6.jpg" alt=""></li>

jQuery stuff
Using jQuery library and jQueryUI we will make .sortable list sortable.

 revert: 100,
 placeholder: 'placeholder'

Now the AJAX

btn_save.on('click', function(e){
  var sortable_data = ul_sortable.sortable('serialize'); 

    data: sortable_data,
    type: 'POST',
    url: 'save.php', // save.php - file with database update

Before we send the data through the PHP (save.php) file, we have to serialize data, which means we have to convert the collected unordered list elements to an Array, that our PHP file reads it with ease.

Finally, the PHP with MySQL

$order = 0;
  foreach ( $array_items as $item) {
    $update = "UPDATE $db_table SET ord = '$order' WHERE id='$item' ";
    $perform = mysql_query( $update ); 
    echo mysql_error();
} else {
  echo 'Connection error';

Conclusion <br>
Using jQuery AJAX, we are sending the unordered list as an Array. Just like that:


Than we fetch it with PHP and run a loop. The loop puts an number in the brackets

$order => item[$order]=1

So that the item element equal to eg 1 has an order of: $order.

Live demo <br>

Download <br>