In this article, we will learn how to drag and drop table rows using jquery ajax with MySQL with toastr.js


My Project structure

php-tutorial/
┣ data.php
┣ dbConfig.php
┗ index.php

Example

First, we need some dummy data to show in the table use the following SQL data to important in your database

php-tutorial.sql

-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jan 26, 2021 at 04:24 PM
-- Server version: 10.4.17-MariaDB
-- PHP Version: 7.3.25

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `php-tutorial`
--

-- --------------------------------------------------------

--
-- Table structure for table `myposts`
--

CREATE TABLE `myposts` (
  `id` int(11) NOT NULL,
  `title` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `postdate` varchar(250) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `myposts`
--

INSERT INTO `myposts` (`id`, `title`, `postdate`) VALUES
(1, 'PUBG Mobile India Full Game Download Android And iOS', '66'),
(2, 'Using htaccess to deny access to files and directories', '50'),
(3, 'Bluestacks - How to play mobile games in PC', '51'),
(4, 'Avada - Website Builder For WordPress and WooCommerce download as free', '36'),
(5, 'Download Farming Simulator 19 For Free 2020', '14'),
(6, 'How To Download Free Grand Theft Auto V For PC', '39'),
(7, 'How to download WhatsApp Desktop Or PC', '17'),
(8, 'Pagination in Codeigniter With Bootstrap 4', '38'),
(9, 'How To Use Phone by Google Caller ID and spam protection App', '41'),
(10, 'Minecraft Caves and Clifs 1.17 Android Download', '70'),
(11, 'PHP Date and Time - complete tutorial for beginners', '8'),
(12, 'High-speed Net - Secret Jio APN Settings', '55'),
(13, 'How to upload multiple files into CodeIgniter', '53'),
(14, 'How to upload multiple files with JavaScript and PHP', '52'),
(15, 'Crash Bandicoot 4 Its About Time Full Game For PC Free Download', '19'),
(16, '5 Easy ways to make money online and quickly', '40'),
(17, 'How to Complete 4000 Hours of Watch Time on YouTube This Year As A Small Creator', '46'),
(18, 'Zip And Unzip Files in Windows Pc', '73'),
(19, 'How To Create And Use Google Form', '26'),
(20, 'How To Create A Paytm Account With KYC', '18'),
(21, 'Fixnow - Plumbing HTML Template download as free', '58'),
(22, 'Tips And Tricks to increase PC performance in Windows 10', '44'),
(23, 'Error 0x80070002 - Windows Update', '11'),
(24, 'How to stop automatic updates on Windows 10', '62'),
(25, 'How to speed up your internet speed', '27'),
(26, 'How to make your Facebook profile as private', '9'),
(27, 'The most effective method to Import CSV file data to MySQL in CodeIgniter', '4'),
(28, 'How to create and use UPI', '30'),
(29, '2 Ways to activate Windows 10 FREE without additional software', '49'),
(30, 'Jio Free Data Tricks 2021', '54'),
(31, 'How To Download Among Us PC For Free', '47'),
(32, 'How can I find out which graphics card I have in my PC', '5'),
(33, 'How to Make Money with Your Blog in 2021', '3'),
(34, 'How to Format USB Flash Drive Using CMD', '57'),
(35, 'Troubleshoot problems updating Windows 10', '20'),
(36, 'How to Create a Bootable Pendrive using cmd', '71'),
(37, '15 best Android games on playstore', '32'),
(38, 'OnePlus 8T buyers guide - Everything you need to know', '15'),
(39, 'PUBG Mobile India Version Latest Update- APK Download LinksAvailable on Official Website', '35'),
(40, '7 Ways to Improve Your Computer Performance', '25'),
(41, 'Top 5 Product Review Website Rating Blog HTML5 Templates', '12'),
(42, 'Top 5 best Android emulators for PC and Mac of 2021', '48'),
(43, 'The best Android phones - January 2021', '60'),
(44, 'Cybersecurity Insights Report On 5G release', '28'),
(45, 'GOOGLE adds a list of new partners with BeyondCorp Alliance', '6'),
(46, 'PUBG Mobile India Download Now Available Beta APK', '61'),
(47, 'Very high resolution images free download', '63'),
(48, 'What is Creative Commons', '64'),
(49, 'What is a public domain', '37'),
(50, 'What is royalty free', '65'),
(51, '15 best Chromebook games from Google Play', '33'),
(52, 'Organizations may fail to train their employees against Cybersecurity Threats', '42'),
(53, 'One Identity Highlights Barriers to Adoption of Zero Trust Framework', '59'),
(54, '5 YouTube tricks to help you raise revenue 50 percentage faster Instantly', '68'),
(55, 'PUBG Mobile 2 global version beta update APK OBB download', '21'),
(56, 'The 15 best Android apps available now', '67'),
(57, 'Can not send or receive messages on your Android phone', '43'),
(58, 'Full Galaxy S21 Ultra specs leak no in-box charger allegedly confirmed', '69'),
(59, 'Google Camera Go now brings HDR to budget smartphones Updated', '13'),
(60, 'Sony returns all Cyberpunk 2077 order renewals: Xbox and refunds for all', '72'),
(61, 'How To Calculate CPC and CTR-Formulas', '75'),
(62, 'How to move the mouse cursor with the keyboard in Windows', '45'),
(63, 'Top 10 Indian Information Technology Companies', '74'),
(64, 'Top Indian Information Technology Companies', '2'),
(65, 'TOP MOST EXPENSIVE MOBILE PHONES IN THE WORD', '56'),
(66, 'Best budget gaming headphones', '1'),
(67, '10 WordPress Tips to Make Your Website Secure', '7'),
(68, 'IPhone12 features How Apples snappy new magnet feature works', '10'),
(69, 'How to Not Get Locked Out With Two-Factor Authentication', '16'),
(70, '10 best reminder apps for Android', '22'),
(71, 'BEST STORY-DRIVEN GAMES ON MOBILE', '23'),
(72, 'Best top 5 Smart TVs in India', '24'),
(73, 'SEO-friendly URLs', '29'),
(74, 'What is Canonical Tag Or link SEO', '31'),
(75, 'How to Increase Website Traffic Tips and Tricks', '34');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `myposts`
--
ALTER TABLE `myposts`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `myposts`
--
ALTER TABLE `myposts`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=149;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


dbConfig.php

<?php

$host = "localhost"; 
$user = "root"; 
$password = ""; 
$dbname = "php-tutorial"; 

$mysqli = mysqli_connect($host, $user, $password, $dbname);
// Check connection
if (!$mysqli) {
    die("Connection failed: " . mysqli_connect_error());
}



index.php

<!DOCTYPE html>
<html>
    <head>
        <title>Drag and Drop Table Rows using toastr.js In PHP Mysql</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css">
        <style type="text/css">
            body{
                background:#d1d1d2;
            }
            .mian-section{
                padding:20px 60px;
                margin-top:100px;
                background:#fff;
            }
            .title{
                margin-bottom:50px;
            }
            .label-success{
                position: relative;
                top:20px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-8 col-md-offset-2 mian-section">
                    <h3 class="text-center title">
                        My Sample Posts
                    </h3>
                    <table class="table table-bordered">
                        <tr>
                            <th>Id</th>
                            <th>Title</th>
                            <th>index</th>
                        </tr>
                        <tbody class="row_position">
                            <?php
                            require('dbConfig.php');
                            $sql = "SELECT * FROM myposts ORDER BY postdate";
                            $posts = $mysqli->query($sql);
                            while ($data = $posts->fetch_assoc()) {
                                ?>
                                <tr id="<?php echo $data['id'] ?>">
                                    <td><?php echo $data['id'] ?></td>
                                    <td><?php echo $data['title'] ?></td>
                                    <td><?php echo $data['postdate'] ?></td>
                                </tr>
                                <?php
                            }
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
        <script type="text/javascript">
            $(".row_position").sortable({
                delay: 150,
                stop: function() {
                    var selectedData = new Array();
                    $('.row_position>tr').each(function() {
                        selectedData.push($(this).attr("id"));
                    });
                    updateOrder(selectedData);
                }
            });
            function updateOrder(data) {
                $.ajax({
                    url: "data.php",
                    type: 'post',
                    data: {position: data},
                    success: function(data) {
                        toastr.success('Your Change Successfully Saved.');
                    }
                })
            }
        </script>
    </body>
</html>


data.php

<?php

// Include Connection File 
require('dbConfig.php');

$position = $_POST['position'];

$i = 1;
// Update Orting Data 
foreach ($position as $k => $v) {

    $sql = "Update myposts SET postdate=" . $i . " WHERE id=" . $v;

    $mysqli->query($sql);

    $i++;
}
?>

thanks for visiting us

Download source code

Are you facing problems in understanding this article? download source code now