Bulk Deletion using Checkbox in PHP and JavaScript Tutorial

Introduction

In this tutorial, you will learn how to Create a Bulk Deletion Feature for web applications using HTML Checkbox, PHP, MYSQL Database, JavaScript, and jQuery/Ajax. This tutorial aims to provide a reference or guide to students or new programmers for the integration of PHP, MySQL Database, and JavaScript to develop an effective and interactive web application. Here, snippets and sample program web application source code are provided.

What is Bulk Deletion?

In a web application, Bulk Deletion is the process of deleting multiple data from the list, table, or database at once. This process or feature is commonly developed using HTML Checkboxes. The said feature can lessen the time to be consumed by the end-user in order to delete multiple data from the web application.

Technologies

Here are the following Technologies used to achieve a Bulk Deletion Feature for this tutorial.

  • XAMPP
  • Code Editor (VS Code, Sublime Text, or Notepad++)
  • PHP
  • MySQL Database
  • HTML
  • CSS
  • JavaScript
  • jQuery Library (not a slim copy)
  • Bootstrap Framework (for the Page Design)

How to Create a Bulk Deletion Feature using Checkbox, PHP, and JS?

Creating the Bulk Deletion Feature using Checkboxes is not that complicated and there are a lot of ways to create one. Here's one of the effective ways to do it.

MySQL Schema and Sample Data

Let us assume that we have the following MySQL Database and Table Schema. The Database name is dummy_db and the sample table is called posts.

  1. CREATE TABLE `posts` (
  2. `title` varchar(250) NOT NULL,
  3. `content` text NOT NULL,
  4. `meta_description` text NOT NULL,
  5. `author` text NOT NULL,
  6.  
  7. INSERT INTO `posts` (`id`, `title`, `content`, `meta_description`, `author`, `created_at`, `updated_at`) VALUES
  8. (1, 'Quos voluptatem delectus sed et.', 'Ullam voluptas nostrum dolore velit odio iusto. Enim est dolorem sint nihil rem. Aut et est similique inventore. Hic ullam perspiciatis ad veritatis.', 'Quaerat quidem molestias autem placeat autem qui.', 'Colby Wilderman', '2012-12-04 21:49:28', NULL),
  9. (2, 'Est et molestiae sunt inventore occaecati.', 'Ut aliquid ipsa quo vitae odit ipsam. Odio labore temporibus fugiat neque doloribus quos incidunt omnis. Perferendis aperiam non vel voluptatem. Molestias nemo odit sit esse quo.', 'Tempore reprehenderit cupiditate consequuntur doloremque quis voluptatem ex ut.', 'Lisa Runolfsdottir', '1972-11-14 04:16:35', NULL),
  10. (3, 'Non aliquid ut et ipsam ut cupiditate et.', 'Quo fugiat nihil aut tenetur aut in. Ut dolores minima cum cumque nobis. Enim cumque omnis repellat tempora. Laudantium in velit omnis nam. Aperiam veritatis aut numquam perspiciatis similique rerum.', 'Fugit tempore modi delectus et.', 'Cleora Legros', '2007-08-15 07:23:17', NULL),
  11. (4, 'Cum omnis assumenda ut quia fugit et saepe vel.', 'Non aliquid voluptas dignissimos est beatae consequuntur mollitia. Quam voluptates eligendi occaecati sapiente sed sint aperiam.', 'Voluptatum et maiores quae cupiditate.', 'Dr. Jerrold Rice', '1989-05-06 00:19:12', NULL),
  12. (5, 'Aut aut magnam tempora.', 'Quibusdam voluptatem hic aut quis neque. Quibusdam recusandae quas vel ipsam hic magnam. Quam quibusdam repudiandae quia dolore expedita nobis.', 'Repellendus itaque asperiores non quisquam alias temporibus doloribus.', 'Juwan Ullrich V', '2001-07-24 23:27:38', NULL);

Database Connection

Next, we need to create a database connection file. This is a PHP File that contains a script for connecting to the MySQL Database. This file will be included in other PHP file scripts that fetch and delete data on the database.

db-connect.php

  1. <?php
  2. $host = "localhost";
  3. $username = "root";
  4. $pw = "";
  5. $db_name = "dummy_db";
  6.  
  7. $conn = new mysqli($host, $username, $pw, $db_name);
  8. if(!$conn){
  9. die('Database connection failed');
  10. }
  11. ?>

Fetching Data

Next, create a PHP file that contains a function that fetches all the data to display from the database.

get_posts.php

  1. <?php
  2. require_once('db-connect.php');
  3.  
  4. function get_posts(){
  5. global $conn;
  6.  
  7. $sql = "SELECT * FROM `posts` order by abs(unix_timestamp(`created_at`)) desc";
  8. $query = $conn->query($sql);
  9. return $query->fetch_all(MYSQLI_ASSOC);
  10. }
  11. $conn->close();

Creating the Interface

Next, create the Page Interface. It is a PHP file that consists of HTML and PHP. The following snippets used Bootstrap and jQuery CDNs which means that an internet connection is a must when running the application in order to load the external Library properly.

index.php

  1. <?php
  2. require_once('get_posts.php');
  3. $posts = get_posts();
  4. ?>
  5. <!DOCTYPE html>
  6. <html lang="en">
  7. <meta charset="UTF-8">
  8. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  9. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  10. <title>Bulk Deletion</title>
  11.  
  12. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  13. <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  14. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  15.  
  16. <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
  17. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  18.  
  19. html, body{
  20. min-height:100%;
  21. width:100%;
  22. }
  23. </style>
  24. </head>
  25. <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  26. <div class="container">
  27. <a class="navbar-brand" href="./">Bulk Deletion</a>
  28. <div>
  29. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  30. </div>
  31. </div>
  32. </nav>
  33. <div class="container px-5 my-3">
  34. <h2 class="text-center">Bulk Deletion of Data using PHP, jQuery, and Ajax</h2>
  35. <div class="row">
  36. <!-- Page Content Container -->
  37. <div class="col-lg-12 col-md-12 col-sm-12 mt-4 pt-4 mx-auto">
  38. <div class="container-fluid">
  39. <div class="card rounded-0 shadow">
  40. <div class="card-header">
  41. <div class="d-flex justify-content-between">
  42. <div class="card-title col-auto flex-shrink-1 flex-grow-1">Page Content</div>
  43. <div class="col-atuo">
  44. <button class="btn btn-danger btn-sm btn-flat d-none" id="delete_btn">Delete Selected Post(s)</button>
  45. </div>
  46. </div>
  47. </div>
  48. <div class="card-body">
  49. <div class="container-fluid">
  50. <table class="table table-stripped table-bordered">
  51. <col width="5%">
  52. <col width="20%">
  53. <col width="20%">
  54. <col width="55%">
  55. <tr>
  56. <th class="text-center">
  57. <input class="form-check-input" type="checkbox" id="selectAll">
  58.  
  59. </th>
  60. <th class="text-center">Title</th>
  61. <th class="text-center">Author</th>
  62. <th class="text-center">Content</th>
  63. </tr>
  64. </thead>
  65. <?php foreach($posts as $post): ?>
  66. <tr>
  67. <td class="text-center">
  68. <input class="form-check-input" type="checkbox" name="post_id[]" value="<?= $post['id'] ?>">
  69. </td>
  70. <td><?= $post['title'] ?></td>
  71. <td><?= $post['author'] ?></td>
  72. <td><div class="" style=""><?= $post['content'] ?></div></td>
  73. </tr>
  74. <?php endforeach; ?>
  75. </tbody>
  76. </table>
  77. </div>
  78. </div>
  79. </div>
  80. </div>
  81. </div>
  82. <!-- End of Page Content Container -->
  83. </div>
  84. </div>
  85. <!-- Confirmation Modal -->
  86. <div class="modal fade" id="confrimModal" data-bs-backdrop="static" aria-labelledby="confrimModal" aria-hidden="true" tabindex="-1">
  87. <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable rounded-0">
  88. <div class="modal-content rounded-0">
  89. <div class="modal-header rounded-0">
  90. <h1 class="modal-title fs-5">Confirmation</h1>
  91. <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
  92. </div>
  93. <div class="modal-body rounded-0">
  94. <div class="container-fluid">
  95. <p>Are you sure to delete to following post(s)? This action cannot be undone.</p>
  96. <ul id="post_to_delete_list"></ul>
  97. </div>
  98. </div>
  99. <div class="modal-footer">
  100. <button type="button" id="confirm-deletion" class="btn btn-danger btn-sm rounded-0">Confirm Deletion</button>
  101. <button type="button" class="btn btn-secondary btn-sm rounded-0" data-bs-dismiss="modal">Close</button>
  102. </div>
  103. </div>
  104. </div>
  105. </div>
  106. <!-- End of Confirmation Modal -->
  107.  
  108. <script src="app.js" ></script>
  109.  
  110. </body>
  111. </html>

Creating the JavaScript

The below snippet is the JavaScript File that contains event listeners functions, modal functionalities, and Ajax scripts. It also contains the script that allows the user to check/uncheck all the row items checkboxes.

app.js

  1. var confirmModal = $('#confrimModal')
  2. var checked_ids = []
  3. var total_checks = $('input[name="post_id[]"]').length;
  4. var total_checks_checked = checked_ids.length
  5. var post_to_delete_list = $('#post_to_delete_list')
  6. $(document).ready(function(){
  7. /**
  8.   * Store Checked Post ID
  9.   */
  10.  
  11. $('input[name="post_id[]"]').change(function(){
  12. var id = $(this).val()
  13. if($(this).is(':checked') === true){
  14. if(($.inArray(id, checked_ids)) < 0)
  15. checked_ids.push(id)
  16. }else{
  17. checked_ids = checked_ids.filter(e => e != id)
  18. }
  19. total_checks_checked = checked_ids.length
  20. if(total_checks_checked == total_checks){
  21. $('#selectAll').prop('checked',true)
  22. }else{
  23. $('#selectAll').prop('checked',false)
  24. }
  25. if(total_checks_checked > 0){
  26. $("#delete_btn").removeClass('d-none')
  27. }else{
  28. $("#delete_btn").addClass('d-none')
  29. }
  30. })
  31.  
  32. /**
  33.   * Select All Function
  34.   */
  35.  
  36. $('#selectAll').change(function(e){
  37. e.preventDefault()
  38. var _this = $(this)
  39. if(_this.is(':checked') === true){
  40. $('input[name="post_id[]"]').prop('checked', true).trigger('change')
  41. }else{
  42. $('input[name="post_id[]"]').prop('checked', false).trigger('change')
  43. }
  44. })
  45.  
  46. /**
  47.   * Delete Confirmation Function
  48.   */
  49. $('#delete_btn').click(function(){
  50. var to_delete = '';
  51. checked_ids.map(id => {
  52. var parent = $(`input[name="post_id[]"][value="${id}"]`).closest('tr')
  53. console.log(`input[name="post_id[]"][value="${id}"]`)
  54. var post_title = parent.find('td:nth-child(2)').text()
  55. to_delete += `<li>${post_title}</li>`;
  56. })
  57. post_to_delete_list.html(to_delete)
  58. confirmModal.modal('show')
  59. })
  60.  
  61. /**
  62.   * Reset Selected List in Confirm Modal
  63.   */
  64.  
  65. confirmModal.on('hide.bs.modal', function(e){
  66. post_to_delete_list.html('')
  67. })
  68.  
  69. /**
  70.   * Delete Confirmed Action
  71.   */
  72.  
  73. $('#confirm-deletion').click(function(e){
  74. e.preventDefault()
  75. var _this = $(this)
  76. _this.attr('disabled', true)
  77. $.ajax({
  78. url:'delete_posts.php',
  79. method:'POST',
  80. data:{ids: checked_ids},
  81. dataType:'json',
  82. error:(err)=>{
  83. console.error(err)
  84. alert("An error occurred while deleting the post(s) data.")
  85. },
  86. success:function(resp){
  87. if(!!resp.status){
  88. if(resp.status == 'success'){
  89. alert("Selected Post(s) Data has been deleted successfully.")
  90. location.reload()
  91. }else if(!!resp.error){
  92. alert(resp.error)
  93. }else{
  94. alert("An error occurred while deleting the post(s) data.")
  95. }
  96. }else{
  97. alert("An error occurred while deleting the post(s) data.")
  98. }
  99. }
  100. })
  101. })
  102.  
  103. })

Creating the Delete API

The following snippet is a PHP Script that processes the deletion of the selected data from the database. The selected data IDs will be sent to this file by the Ajax script using the POST method.

delete_posts.js

  1. <?php
  2. require_once('db-connect.php');
  3. if($_SERVER['REQUEST_METHOD'] == 'POST'){
  4. $ids = isset($_POST['ids']) ? $_POST['ids'] : [];
  5. if(count($ids) > 0){
  6. $sql = "DELETE FROM `posts` where `id` IN (".(implode(",", $ids)).")";
  7. $delete = $conn->query($sql);
  8. if($delete){
  9. $resp['status'] = 'success';
  10. }else{
  11. $resp['status'] = 'failed';
  12. $resp['error'] = $conn->error;
  13. }
  14. }else{
  15. $resp['status'] = 'failed';
  16. $resp['error'] = 'No Post ID(s) Data sent to delete.';
  17. }
  18. }else{
  19. $resp['status'] = 'failed';
  20. $resp['error'] = 'No Post Data sent to this current request.';
  21. }
  22.  
  23. echo json_encode($resp);
  24.  
  25. $conn->close();

That's it! You can now test the sample web application that contains a Bulk Deletion Feature on your end.

How does the Application work?

  1. Check the data you desire to delete or check the checkbox located at the upper left of the table trigger check all the checkboxes.
  2. After you check at least 1-row checkbox, the Delete Selected Post(s) Button will appear on the right side of the panel or card title container.
  3. A Confirmation Modal will appear after clicking the Delete Selected Post(s) Button. The modal contains a message confirming that you are about to delete selected Post(s) Data. Selected posts' titles are listed also on the confirmation modal.
  4. Click the Confirm Deletion Button to confirm the deletion of data.

Application Snapshots

Main Page

bulk Deletion - Main Page

Confirmation Modal

bulk Deletion - Confirmation Modal

DEMO VIDEO

That's the end of this tutorial. I hope this Bulk Deletion using Checkboxes, PHP, MySQL, and JS tutorial will help you with what you are looking for and that you'll find this useful for your current or future PHP Projects.

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

Happy Coding :)

Add new comment