Share this:

In this tutorial we are going to learn how to drag & drop reorder images in PHP. Drag and Drop feature is very useful and user friendly for your visitors. This helps your visitor’s to arrange the images to there desire order.

We are using JQuery and JQuery UI by using this its become easy to implement. The jQuery UI provides an easy way to add draggable functionality to the DOM element.

This tutorial will cover drag and drop feature to sort the database images list dynamically.

The example code helps to implement dynamic drag and drop reorder images using jQuery, Ajax, PHP, and MySQL. This sample code also can be used to implement the drag and drop reorder the list, rows, or sorting elements.

Also Read : Install ReactJS in Laravel 9 Tutorial

Steps for Drag & Drop Reorder Images in PHP (2022)

  • Step 1: Files Structures
  • Step 2: Create Database & Table
  • Step 3: Create DB Class (DB.class.php)
  • Step 4: Download JQuery and JQuery UI
  • Step 5: Create PHP & HTML Code (index.php)
  • Step 6: Create orderUpdate.php File
  • Step 7: Create Stylesheet (style.css)
  • Step 8: Testing
  • Step 9: Conclusion

Files Structures

So, Before starting the tutorial first we know the file’s structures by looking at the below image:

Files Structures - Drag & Drop Reorder Images in PHP (2022)

Create Database & Table

Now, It’s time to create a database and table. To create a database first open phpmyadmin page the create a new database with name anything you like we use drag_drop_reorder_images.

Create database for drag & drop reorder images in php

So after creating a database. Now, we are going to create an images table. To create a images table enter the below code to SQL Query and run.

CREATE TABLE `images` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `file_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `img_order` int(5) NOT NULL DEFAULT '0',
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Query to create images table

This will create a images table and add some records as shown in the below image.

Also Read : How to send mail using Gmail in Laravel 9?

Create DB Class (DB.class.php)

Create a DB.class.php file to the root of the directory and add the following code to the file:

<?php

class DB{
    //Database Config
    private $dbHost = "localhost";
    private $dbUsername = "root";
    private $dbPassword = "";
    private $dbName = "drag_drop_reorder_images";
    private $imgTbl = 'images';

    function __construct(){
        if(!isset($this->db)){
            //connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);

            if($conn->connect_error){
                die("Failed to connect with MySql : " . $conn->connect_error);
            }else{
                $this->db = $conn;
            }
        }
    }

    //Get rows from images table
    function getRows(){
        $query = $this->db->query("SELECT * FROM " . $this->imgTbl . " ORDER BY img_order ASC");

        if($query->num_rows > 0){
            while($row = $query->fetch_assoc()){
                $result[] = $row;
            }
        }else{
            $result = FALSE;
        }

        return $result;
    }

    //Update Image Order
    function updateOrder($id_array){
        $count = 1;

        foreach($id_array as $id){
            $update = $this->db->query("UPDATE " . $this->imgTbl . " SET img_order = $count, modified = NOW() WHERE id = $id");
            $count++;
        }

        return TRUE;
    }
}

So, DB class controls all the database work which is connect, fetch and update the records. Please Specify $dbHost, $dbUsername, $dbPassword, $dbName as per your MySQL database credentials.

There are three functions:

  • __construct() – __construct() function is for connecting database.
  • getRows() – getRows() function retrieve the images data from the database.
  • updateOrder() – updateOrder() function update list order of the images.

Download JQuery and JQuery UI

Now, We require JQuery and JQuery UI for our project. So, Next we will download them.

Download JQuery and JQuery UI.

Download JQuery
JQUERY
Download JQuery UI
JQUERY UI

Add jquery-ui.min.js and jquery.min.js into js folder as show in the below image.

Create PHP & HTML Code (index.php)

It’s time to create PHP and HTML (index.php) file. Create a new index.php file into the root of the directory and add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Drag & Drop Reorder Images in PHP - LaravelTuts</title>

    <link rel="stylesheet" href="css/style.css">
    <script src="js/jquery.min.js"></script>
    <script src="js/jquery-ui.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function(){
            $('.reorder_link').on('click', function(){
                $("ul.reorder-photos-list").sortable({ toterance : 'pointer' });
                $('.reorder_link').html('Save Reordering');
                $('.reorder_link').attr("id","saveReorder");
                $('#reorderHelper').slideDown('slow');
                $('.image_link').attr("href","javascript:void(0);");
                $('.image_link').css("cursor","move");

                $('#saveReorder').click(function(e){
                    if(!$("#saveReorder i").length){
                        $(this).html('').prepend('<img src="images/refresh-animated.gif" />');
                        $("ul.reorder-photos-list").sortable('destroy');
                        $("#reorderHelper").html("Reordering Photos - This could take a moment. Please don't navigate away from this page.").removeClass('light_box').addClass('notice notice_error');

                        var h = [];

                        $("ul.reorder-photos-list li").each(function(){
                            h.push($(this).attr('id').substr(9));
                        });

                        $.ajax({
                            type: "POST",
                            url: "orderUpdate.php",
                            data: { ids: " " + h + ""},
                            success: function(){
                                window.location.reload();
                            }
                        });

                        return false;
                    }
                    e.preventDefault();
                });

            });
        });
    </script>
</head>
<body>
    <div class="container">
        <a href="javascript:void(0);" class="reorder_link" id="saveReorder">Reorder Photos</a>

        <div id="reorderHelper" class="light_box" style="display:none;">
            1. Drag Photos to Reorder<br/>
            2. Click 'Save Reoreding' when finished
        </div>

        <div class="gallery">
            <ul class="reorder_ul reorder-photos-list">
                <?php
                    //include and create instance of DB class
                    require_once 'DB.class.php';
                    $db = new DB();

                    //Fetch all images from database
                    $images = $db->getRows();
                    if(!empty($images)){
                        foreach($images as $row){
                        ?>
                            <li id="image_li_<?php echo $row['id']; ?>" class="ul-sortable-handle">
                                <a href="javascript:void(0);" style="float:none;" class="image_link">
                                    <img src="images/<?php echo $row['file_name']; ?>" alt="">
                                </a>
                            </li>
                        <?php
                        }
                    }
                ?>
            </ul>
        </div>

    </div>
</body>
</html>

Also Read : Create CRUD Application with Laravel and Vue.js

Create orderUpdate.php File

Now, Its time to create orderUpdate.php. Create a orderUpdate.php file into the root of the directory and add the following code:

<?php

//Include and Create instance of DB Class
require_once 'DB.class.php';
$db = new DB();

//Get Images id and generate ids array
$idArray = explode(",", $_POST['ids']);

//Update images order
$db->updateOrder($idArray);

?>

Create Stylesheet (style.css)

Now, we will create stylesheet of design our html. Create a new file style.css in css folder and add the following stylesheet into it:

.container{
    margin-top: 50px;
    padding: 10px;
}
ul, ol, li{
    margin: 0;
    padding: 0;
    list-style: none;
}
.reorder_link{
    color: #367584;
    border: solid 2px #367584;
    border-radius: 3px;
    text-transform: uppercase;
    background: #fff;
    font-size: 18px;
    padding: 10px 20px;
    margin: 15px 15px 15px 0;
    font-weight: bold;
    text-decoration: none;
    transition: all 0.35s;
    -moz-transition: all 0.35s;
    -webkit-transition: all 0.35s;
    -o-transition: all 0.35s;
    white-space: nowrap;
}
.reorder_link:hover{
    color: #fff;
    border: solid 2px #367584;
    background: #367584;
    box-shadow: none;
}
#reorder-helper{
    margin: 18px 10px;
    padding: 10px;
}
.light_box{
    background: #efefef;
    padding: 20px;
    margin: 15px 0;
    text-align: center;
    font-size: 1.2em;
}
/* Image Gallery */
.gallery{
    width: 100%;
    float: left;
    margin-top: 15px;
}
.gallery ul{
    margin: 0;
    padding: 0;
    list-style-type: none;
}
.gallery ul li{
    padding: 7px;
    border: 2px solid #ccc;
    float: left;
    margin: 10px 7px;
    background: none;
    width: auto;
    height: auto;
}
.gallery img{
    width: 250px;
}

/* Notice Box */
.notice, .notice a{
    color: #fff;
}
.notice{
    z-index: 8888;
    padding: 10px;
    margin-top: 20px;
}
.notice a{
    font-weight: bold;
}
.notice_error{
    background: #E46360;
}
.notice_success{
    background: #657E3F;
}

Testing

That it! All Done! Now its time to test our PHP application.

Testing – Drag & Drop Reorder Images in PHP (2022)

Conclusion

Today, We had learned Drag & Drop Reorder Images in PHP (2022) with Ajax and JQuery. Hope this tutorial help you. If you have any trouble with the code ask us at comment section below.

Also Read : Create a custom WordPress Plugin from scratch (2022)

Share this:

Categorized in: