This is very common feature that items list need to drag and drop and save it. Drag’n drop generally looks hard-to-apply but it is definitely not by using JavaScript frameworks. In this article i will show how the drag’n drop & saving the new positions to the database Will be working”. This is very simple process you can apply it. This is simple code which you can check

First create a simple database Suppose “drag” . Here is the code for create a table then run this code in mysql

CREATE TABLE `records` (
 `recordID` int(11) NOT NULL auto_increment,
 `recordText` varchar(255) default NULL,
 `recordListingID` int(11) default NULL,
 PRIMARY KEY (`recordID`)
 );
 
INSERT INTO `records` VALUES ('1', 'Once dropped, an Ajax query is activated', '3');
 INSERT INTO `records` VALUES ('2', 'Dragging changes the opacity of the item', '2');
 INSERT INTO `records` VALUES ('3', 'Returned array can be found at the right', '1');
 INSERT INTO `records` VALUES ('4', 'It is very very easy', '4');

The most important column in the database is recordListingID which shows us the order of the records.

Then create a php page which ready mysql connect .

<?php
/*
* Author : Ali Aboussebaba
* Email : bewebdeveloper@gmail.com
* Website : http://www.bewebdeveloper.com
* Subject : Dynamic Drag and Drop with jQuery and PHP
*/

// PDO connect *********
function connect() {
	$host = 'localhost';
	$db_name = 'drag';
	$db_user = 'root';
	$db_password = '';
    return new PDO('mysql:host='.$host.';dbname='.$db_name, $db_user, $db_password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
?>

Then create index.php which is the main page to view list

<!DOCTYPE>
<html>
<?php
include('config.php');
$pdo = connect();
$sql = 'SELECT * FROM records ORDER BY recordListingID ASC';
$query = $pdo->prepare($sql);
$query->execute();
$list = $query->fetchAll();

?>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>jQuery Dynamic Drag'n Drop</title>
    <script type="text/javascript" src="http://techparkbd.com/subdomain/source_file/jquery-1.10.2.js"></script>
    <script type="text/javascript" src="http://techparkbd.com/subdomain/source_file/jquery-ui-1.10.4.custom.min.js"></script>

    <style>
        body {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 16px;
            margin-top: 10px;
        }

        ul {
            margin: 0;
        }

        #contentWrap {
            width: 700px;
            margin: 0 auto;
            height: auto;
            overflow: hidden;
        }

        #contentTop {
            width: 600px;
            padding: 10px;
            margin-left: 30px;
        }

        #contentLeft {
            float: left;
            width: 400px;
        }

        #contentLeft li {
            list-style: none;
            margin: 0 0 4px 0;
            padding: 10px;
            background-color:#00CCCC;
            border: #CCCCCC solid 1px;
            color:#fff;
        }

        #contentRight {
            float: right;
            width: 260px;
            padding:10px;
            background-color:#336600;
            color:#FFFFFF;
        }

    </style>
    <script type="text/javascript">
        $(document).ready(function(){

            $(function() {
                $("#contentLeft ul").sortable({ opacity: 0.6, cursor: 'move', update: function() {
                    var order = $(this).sortable("serialize");
                    $.ajax({
                        url: 'http://localhost/updatelist.php?action=updateRecordsListings',
                        type: 'POST',
                        data: order,
                        success: function (result) {
                            $("#contentRight").html(result);
                        }
                    });
                }
                });
            });

        });
    </script>

</head>
<body>

<div id="contentWrap">
    <div id="contentLeft">
        <ul>
            <?php
            foreach ($list as $rs) {
                ?>
                <li id="recordsArray_<?=$rs['recordID']?>"><?=$rs['recordText']?></li>
                <?php
            }
            ?>
        </ul>
    </div>

    <div id="contentRight">
        <p>New List will be displayed here.</p>
        <p>&nbsp; </p>
    </div>

</div>

</body>
</html>


After posting the array of “new order of the items” to updatelist.php, we must run a query to update our database that will reflect the last positions of every item:

<?php
include('config.php');
$pdo = connect();

$action = $_GET['action'];
$updateRecordsArray = $_POST['recordsArray'];

if ($action == "updateRecordsListings"){

    $listingCounter = 1;
    foreach ($updateRecordsArray as $recordIDValue) {

        $query = "UPDATE records SET recordListingID = " . $listingCounter . " WHERE recordID = " . $recordIDValue;
        $query = $pdo->prepare($query);
        $query->execute();
        $listingCounter = $listingCounter + 1;
    }

    echo '<pre>';
    print_r($updateRecordsArray);
    echo '</pre>';
    echo 'If you refresh the page, you will see that records will stay just as you modified.';
}
?>

all done so run index.php and drag list , it will automatically save drag list and after refresh it will show new list

This is example output


this is output

Comment