Creating a Dynamic Ordering Data using PHP, MySQL, and JavaScript Tutorial

In this tutorial, you can learn to create Dynamic Ordering Data and DOM Elements using PHP, JavaScript, and MySQL Database. This tutorial aims to provide students and beginners with a reference for learning some useful techniques for building an application using PHP Language, MySQL, and JavaScript. Here, I will be providing a simple web application that demonstrates the main objective of this tutorial. The complete source code zip file will be provided also and is free to download.

What is Dynamic Ordering Data?

Dynamic Ordering Data is a simple web application database table structure that allows the user to choose or set their desired order of data. Basically, we can simply sort the data order by each column on the database but in some instances, we will be forced to implement this kind of structure and add some interactive feature to front-end of a software or application to meet our requirements. For example, an application has a dynamic navigation menu data whereas the developer saves the menu data on the database. Using this kind of database structure, we can sort the order of the menu items for display dynamically.

How to create Dynamic Ordering Data and DOM Elements?

Dynamic Ordering Data and DOM Elements can be achieved using PHP, JavaScript, and MySQL Database. On the database table that we want to dynamically sort the order, we can simply add a column with an integer type of value. The added table column will store the order number of each data. Next, using CSS and JavaScript, we can create a list item element that allows the users to drag and drop the element from the current position to another. Then, using PHP, we can update the new sort order of the data on the database. Check out the sample web application scripts that I created and provided below to understand it more.

Sample Web Application

The scripts below result in a simple web application that contains a simple list of items in which each item is being retrieved from the database. Users can change the order position of the data by grabbing the data element from the current position and dropping it before or after the list item. Then, by hitting or clicking the "Save Order" button, the new sort order of the data will be updated on the database.

Before we start the coding part, please make sure to have virtual server software such as XAMPP, WAMP, or any similar software to allow your local machine to run PHP scripts. Also, make sure to run Apache and MySQL.

Creating the Database

First, on your MySQL Database, create a new database named dummy_db. Copy and Paste the DB Schema and sample data below.

  1. -- phpMyAdmin SQL Dump
  2. -- version 5.1.3
  3. -- https://www.phpmyadmin.net/
  4. --
  5. -- Host: 127.0.0.1
  6. -- Generation Time: Apr 28, 2023 at 09:34 AM
  7. -- Server version: 10.4.24-MariaDB
  8. -- PHP Version: 8.1.5
  9.  
  10. SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
  11. SET time_zone = "+00:00";
  12.  
  13. --
  14. -- Database: `dummy_db`
  15. --
  16.  
  17. -- --------------------------------------------------------
  18.  
  19. --
  20. -- Table structure for table `sampletbl`
  21. --
  22.  
  23. CREATE TABLE `sampletbl` (
  24. `id` int(1) NOT NULL,
  25. `content` text NOT NULL,
  26. `sort_order` tinyint(3) NOT NULL
  27.  
  28. --
  29. -- Dumping data for table `sampletbl`
  30. --
  31.  
  32. INSERT INTO `sampletbl` (`id`, `content`, `sort_order`) VALUES
  33. (1, 'Sample Data Only #1', 0),
  34. (2, 'Sample Data Only #2', 1),
  35. (3, 'Sample Data Only #3', 2),
  36. (4, 'Sample Data Only #4', 3),
  37. (5, 'Sample Data Only #5', 4);
  38.  
  39. --
  40. -- Indexes for dumped tables
  41. --
  42.  
  43. --
  44. -- Indexes for table `sampletbl`
  45. --
  46. ALTER TABLE `sampletbl`
  47. ADD PRIMARY KEY (`id`);
  48.  
  49. --
  50. -- AUTO_INCREMENT for dumped tables
  51. --
  52.  
  53. --
  54. -- AUTO_INCREMENT for table `sampletbl`
  55. --
  56. ALTER TABLE `sampletbl`
  57.  

Creating the Database Connection

Next, create a new PHP file and save it as db-connect.php. Then paste the following script to this file script. This script connects our web application to the MySQL Database that we created.

getMessage()); exit; }

Creating the Page Interface

Next, let's create the page interface of the web application. On your source code directory, create a new PHP file named index.php and copy/paste the code below.

  1. <?php
  2. require_once('db-connect.php')
  3. ?>
  4. <!DOCTYPE html>
  5. <html lang="en">
  6. <meta charset="UTF-8">
  7. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  8. <title>Dynamic Ordering</title>
  9. <link rel="stylesheet" href="style.css">
  10. <link rel="preconnect" href="https://fonts.googleapis.com">
  11. <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  12. <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200" />
  13. </head>
  14. <div class="container">
  15. <h1 id="page-title">Creating a Dynamic Ordering list Item JS, PHP, and MySQL</h1>
  16. <hr id="title_hr">
  17. <form action="update_order.php" method="POST" id="dynamic-order">
  18. <!-- Sortable list Container -->
  19. <div class="sortable-list-container">
  20. <!-- List Wrapper -->
  21. <ul>
  22. <?php
  23. $list_qry = $conn->query("SELECT * FROM `sampletbl` order by `sort_order` asc ");
  24. while($row = $list_qry->fetch_assoc()):
  25. ?>
  26. <!-- List item -->
  27. <li draggable="true">
  28. <div class="flex-container">
  29. <div>
  30. <span class="material-symbols-outlined">
  31. drag_indicator
  32. </span>
  33. </div>
  34. <div>
  35. <input type="hidden" name="sort_order[]" value="<?= $row['id'] ?>">
  36. <?= $row['content'] ?>
  37. </div>
  38. </div>
  39. </li>
  40. <!-- List item -->
  41. <?php endwhile; ?>
  42. </ul>
  43. <!-- List Wrapper -->
  44. </div>
  45. <!-- Sortable list Container -->
  46. </form>
  47. <!-- Form Submit Button -->
  48. <button id="save-btn" type="submit" form="dynamic-order">Save Order</button>
  49. </div>
  50.  
  51. <script src="script.js"></script>
  52. </body>
  53. </html>

Then, create a new file named style.css and use the following script. The script below contains the CSS (stylesheet) code that designs the page layout and other elements of the page.

  1. @import url('https://fonts.googleapis.com/css2?family=Dongle:wght@300;400;700&family=Roboto+Mono:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;1,100;1,200;1,300;1,400;1,500;1,600&display=swap" rel="stylesheet');
  2. *{
  3. margin: 0;
  4. padding: 0;
  5. box-sizing: border-box;
  6. font-family: 'Dongle', sans-serif;
  7. font-family: 'Roboto Mono', monospace;
  8. }
  9. ::selection{
  10. color: #fff;
  11. background: #4db2ec;
  12. }
  13. body{
  14. display: flex;
  15. align-items: center;
  16. justify-content: center;
  17. min-height: 100vh;
  18. background: #4facfe;
  19. background-image: linear-gradient(to right, #4facfe 0%, #00f2fe 100%);
  20. padding: 2em 0;
  21. }
  22. #page-title{
  23. color: #fff;
  24. text-align: center;
  25. font-weight: 500;
  26. text-shadow: 0px 0px 15px #0000003a;
  27. }
  28. #title_hr{
  29. width:60px;
  30. border: 2px solid #ffffff;
  31. margin: .35em auto;
  32. }
  33. @media (min-width: 780px){
  34. #page-title{
  35. width: 780px;
  36. }
  37. }
  38.  
  39.  
  40. /* Sortable List */
  41. .sortable-list-container{
  42. width: 400px;
  43. background-color: #fff;
  44. border: 1px solid #dedede;
  45. box-shadow:1px 1px 5px #6c6c6c;
  46. margin: 1em auto ;
  47. }
  48. .sortable-list-container ul{
  49. padding: .5em 1em;
  50. }
  51. .sortable-list-container ul li{
  52. list-style: none ;
  53. border: 1px solid #cfcfcf;
  54. box-shadow:1px 1px 5px #a8a8a8;
  55. margin-bottom: 10px;
  56. padding: 0.5em 1em;
  57. cursor: grab;
  58. background: #fff;
  59. }
  60. .sortable-list-container ul li[data-dragging="true"]{
  61. border-style: dashed;
  62. box-shadow: unset;
  63. }
  64. .sortable-list-container ul li[data-dragging="true"] :where(*){
  65. opacity: 0;
  66. }
  67.  
  68. /* Flex Container */
  69. .flex-container{
  70. display: flex;
  71. width: 100%;
  72. flex-wrap: wrap;
  73. align-items: center;
  74. }
  75.  
  76. /* Save Button */
  77. button#save-btn {
  78. display: block;
  79. width: 150px;
  80. background: #438efe;
  81. padding: 0.5em 1em;
  82. color: #fff;
  83. font-size: 1rem;
  84. font-weight: 500;
  85. margin: 0.35em auto;
  86. border: none;
  87. box-shadow: 0px 0px 10px #00000030;
  88. cursor: pointer;
  89. }
  90. button#save-btn:hover{
  91. background: #2578f5;
  92. }
  93.  

Creating the Update API

Lastly, let's create a new PHP file named update_order.php and use the following script. This file script will execute the update process of the new sort order of data into the database table.

  1. <?php
  2. // Require or include once the db connection handler script
  3. require_once('db-connect.php');
  4.  
  5. if($_SERVER['REQUEST_METHOD'] == 'POST'){
  6. // If Post data exists
  7. if(isset($_POST['sort_order'])){
  8. // If Sort Order Sample Post data Exists
  9. // set post data into a variable
  10. $data_ids = $_POST['sort_order'];
  11.  
  12. // loop the data
  13. foreach($data_ids as $order => $id){
  14. // update the sort order of the data
  15. $update = $conn->query("UPDATE `sampletbl` set `sort_order` = '{$order}' where `id` ='{$id}'");
  16. if(!$update){
  17. // If query execution fails, return an error message
  18. echo "<script>alert('An error occured while updating data!'); location.replace('./')</script>";
  19. }
  20. }
  21. echo "<script>alert('Data Sort Order has been updated successfully!'); location.replace('./')</script>";
  22. }else{
  23. // No Sort Order Post Data sent
  24. echo "<script>alert('No Sort Data sent!'); location.replace('./')</script>";
  25. }
  26. }else{
  27. // If no post data send to this request
  28. echo "<script>alert('No Post Data sent!'); location.replace('./')</script>";
  29. }

Snapshots

Here are some snapshots of the overall result of the web application script I have provided above:

Default

Creating a Dynamic Ordering Data using PHP, MySQL, and Database

Sample Updated Sort Order #1

Creating a Dynamic Ordering Data using PHP, MySQL, and Database

Sample Updated Sort Order #2

Creating a Dynamic Ordering Data using PHP, MySQL, and Database

DEMO VIDEO

There you go! I have provided the complete source code zip file of the sample web application script I created on this site and it is free to download. The download button can be found below this tutorial's content. Feel free to download and do some experiments with the source code to enhance your programming capabilities.

That's it! I hope this Dynamic Ordering Data and DOM Element using PHP, MySQL, and JavaScript Tutorial will help you with what you are looking for and will be useful for your current and future web application projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)

Add new comment