• Skip to main content
  • Skip to secondary menu
  • Skip to primary sidebar
  • Skip to secondary sidebar

CodingStatus

- Level Up Your Status with Coding Expertise!

  • Tutorials
    • React Js Tutorials
    • JavaScript Tutorials
    • PHP Tutorials
    • HTML Tutorials
    • SQL Tutorials
    • Laravel Tutorials
  • Snippets
    • React Js Code Snippets
    • Ajax Code Snippets
    • Node.js Code Snippets
    • JavaScript Code Snippets
    • jQuery Code Snippets
    • SQL Code Snippets
  • Programs
    • PHP Program
    • Python Programs
    • Java Programs
  • How To
    • React Js How To
    • Node Js How To
    • Ajax How To
    • PHP How To
    • jQuery How To
    • JavaScript How to
  • Scripts
    • PHP Script
    • Js Script
    • React Js Script
    • JQuery Script
  • Projects
    • PHP Project
  • Interview Questions
  • Guide
  • API Integration
  • Installation

Delete Multiple Records with Checkboxes in PHP & MySQL

February 23, 2023 By Md Nurullah

In this tutorial, You will learn to delete multiple records with checkboxes in PHP and MYSQL step by step. Even You will get a complete source code that will be very easy to integrate into your website.

Generally, We need to delete display the largest records of data in the HTML table. It is very inconvenient to delete all or multiple records one by one and It also takes more must time. So, You need to implement a bulk delete feature in your project.

In the case of Bulk delete functionality, you can easily delete all or multiple records from the MySQL Database at once by selecting using checkboxes.php delete multiple records

Table of Contents

  • Delete Multiple Rows From MySQL Database with PHP
    • 1. Connect MySQL Database
    • 2. Fetch and delete multiple records from the database
    • 3. Display Multiple records with checkboxes
    • 4. Select Multiple records with checkboxes

Delete Multiple Rows From MySQL Database with PHP

Now, Let’s start coding to delete multiple rows from the MySQL database from the next steps. But getting started, You should have already stored records in the database. Otherwise, first of all, you will have to insert data into the database using PHP & MYSQL then start coding for deleting data from the database.

myproject/
   |__backend.php
   |__custom.js
   |__ rocords-table.html

Learn Also –

Check Uncheck All checkboxes with a single checkbox using-jquery

Integrate Google ReCAPTCHA using PHP

Create Admin Panel Template in PHP

Let’s start its coding from the next steps –

1. Connect MySQL Database

First of all, connect the MYSQL database to PHP using the following SQL query in PHP

File Name – database.php

<?php
$hostName = "localhost";
$userName = "root";
$password = "";
$databaseName = "codingstatus";
 $conn = new mysqli($hostName, $userName, $password, $databaseName);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
?>

2. Fetch and delete multiple records from the database

To fetch and delete multiple records from the database, you will have to implement the following points –

  • First of all, You should include database.php to connect the database
  • check checkedId (checkbox name of multiple records) and deleteAll (checkbox name of the select all ) are set or not using $_POST. If both are set then call the deleteMultipleData()

fetch_data() – This function accept a single parameters $conn returns all records from that database.

deleteMultipleData() – This function will execute when you check records & click the delete all button and then It will delete the checked records from the database. It mainly accepts two parameters $conn and $checkedId.

Fil Name – backend.php

<?php
include("database.php");

if(isset($_POST['checkedId']) && isset($_POST['deleteAll'])){
  $checkedId = $_POST['checkedId'];
  $deleteMsg=deleteMultipleData($conn, $checkedId);

}
$fetchData = fetch_data($conn);

function fetch_data($conn){
  $query = "SELECT id, fullName, gender, email, city FROM developers ORDER BY id DESC";
  $result = $conn->query($query);

   if ($result->num_rows > 0) {
      $row= mysqli_fetch_all($result, MYSQLI_ASSOC);
      $data= $row;
   } else {
      $data= []; 
   }
     return $data;
}

function deleteMultipleData($conn, $checkedId){
  
$checkedIdGroup = implode(',', $checkedId);
$query = "DELETE FROM developers WHERE id IN ($checkedIdGroup)";
$result = $conn->query($query);
if($result==true){
  return "Selected data was deleted successfully";
}

}
?>

 

3. Display Multiple records with checkboxes

To display multiple records with checkboxes, you will have to implement the following steps –

  • You have to include backend.php that contains code to delete & fetch data
  • You must include the following jquery CDN to execute the jquery code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  • Also, include the custom.js to add a check and uncheck records functionality
<script type="text/javascript" src="custom.js"></script>
  • Create HTML table with checkboxes input and display records by fetching from the database

File Name – records-table.php

<?php
include("backend.php");
?>
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <script type="text/javascript" src="custom.js"></script>
</head>
<body>
<div class="container">
 <div class="row">
   <div class="col-sm-8">
    <h3 class="text-danger text-center">Delete Multiple Records with Checkbox in PHP</h3>
    <p><?php echo $deleteMsg??'';?></p>
    <div class="table-responsive">
   <form method="post" id="deleteForm">
      <table class="table table-bordered table-striped ">
       <thead><tr><th>S.N</th>

         <th>Full Name</th>
         <th>Gender</th>
         <th>Email</th>
         <th>City</th>
         
    </thead>
    <tbody class="checkbox-group">
  <?php

      if(count($fetchData)>0){      
      foreach($fetchData as $data){
    ?>
      <tr>
      <td><input type="checkbox" name="checkedId[]" value="<?php echo $data['id']??''?>"></td>
      <td><?php echo $data['fullName']??''; ?></td>
      <td><?php echo $data['gender']??''; ?></td>
      <td><?php echo $data['email']??''; ?></td>
      <td><?php echo $data['city']??''; ?></td>
      
     </tr>
     <?php
      }}else{ ?>
      <tr>
        <td colspan="8">
        <?php echo "No Data Found"; ?>
        </td>
      <tr>
    <?php }?>
     </tbody>
    <?php 
    if(count($fetchData)>0){  
    ?>
     <tfoot>
    <tr>
      <td><input type="checkbox" id="singleCheckbox" ></td>
      <td class="text-danger">Check All</td>
      <td colspan="7"><input type="submit" name="deleteAll" value="Delete All" class="bg-danger text-light"></td>
    </tr>
     <tfoot>
     <?php } ?>
     </table>
   </tfoot>
   </div>
</div>
</div>
</div>
</body>
</html>

4. Select Multiple records with checkboxes

To select multiple records, you will have to implement the following points –

  • Apply the submit event on id  #deleteForm and call confirmDeleteData() function for confirmation to delete data.
  • Also, create checkUncheck() function and implement the follwing steps within it and called it within $(document).ready().
  • Assign an id “#singleCheckbox” to a variable #singleCheckbox
  • Also, assign “.checkbox-group input[type=’checkbox’]” to another variable checkboxGroup
  • Apply click event on singleCheckbox with the following condition
    • If singleCheckbox is checked then all checkboxes will be checked otherwise all checkboxes will be unchecked
  • If any single of checkbox group is unchecked then a single checkbox to check all will be unchecked

File Name – custom.js

$(document).ready(function(){

   checkUncheck();

   $("#deleteForm").on("submit", function(event){
    confirmDeleteData(event);

});

});



function checkUncheck(){
    const boxsingleCheck = '#singleCheckbox';
    const checkboxGroup = ".checkbox-group input[type='checkbox']";

    if($(document).find(boxsingleCheck).length!==0 || $(document).find(checkboxGroup).length!==0){
    $(singleCheckbox).on('click',function(){
        if(this.checked){
            $(checkboxGroup).each(function(){
                this.checked = true;
            });
        }else{
             $(checkboxGroup).each(function(){
                this.checked = false;
            });
        }
    });
    
    $(checkboxGroup).on('click',function(){
        if($(checkboxGroup+':checked').length == $(checkboxGroup).length){
            $(boxsingleCheck).prop('checked',true);
        }else{
            $(boxsingleCheck).prop('checked',false);
        }
    });
}
}
function confirmDeleteData(event){
    if($(".checkbox-group input[type='checkbox']:checked").length > 0){
        var conformation = confirm("Are you sure to delete selected data?");
        if(conformation==false){
            event.preventDefault();
        }
    }else{
        alert('Check at least 1 record to delete.');
        return false;
    }
}

Filed Under: Uncategorized

Hello Developer, Welcome to my Blog. I'm Md Nurullah, a software engineer with 5+ years in full-stack web development. As the founder of CodingStatus.com, I'm passionate about sharing coding knowledge and collaborating for a brighter future. Let's connect and code together!

Primary Sidebar

Secondary Sidebar

  • SELECT 3rd Highest Salary in SQL
  • How to create reusable input field in react Js
  • How to Create Reusable Select Field in React Js
  • How to Create Reusable Textarea Field in React Js
  • HTML Paragraph Tag
  • React Class Components with Props
  • Check Armstrong Number in Python
  • PHP echo Statement
  • Check Leap Year in Java
  • Check Leap Year in Python
  • Print prime numbers from 1 to n in python
  • React App with CDN
  • React Js Tutorial
  • Introduction to React Js
  • What is React Js
  • Create React App with NPM
  • React App Folder Structure
  • React Components
  • PHP Variable Scope
  • React Function Component
  • React Function Component with Props
  • React Export and Import Function components
  • React Class Component
  • ReactDOM.render() Method in react js
  • ReactDOM.createRoot() in React Js
  • React Fragment
  • Render Method in React Js – render()
  • How to Check two objects are Equal in JavaScript
  • Dynamic Multi-Step Form in React Js
  • PHP Variables – Step By Step Guide
  • Check Prime Number in Java
  • How to use props in Class Component
  • How to Code HTML
  • Dynamic tree view in React JS
  • JavaScript Word Guessing Game
  • Detect an Internet Connection using JavaScript
  • Simple Calculator in React Js
  • Get Query String Value From URL Using JavaScript
  • How to Insert Form Data Into the Table Using Node.js and MySQL
  • How to display Data from MySQL database table in Node.js
  • Load Records on Select Box using Ajax, PHP & MySQL
  • Swapping of Two Numbers in python
  • How to Install Express Application Using Express Generator Tool
  • Registration Form using Ajax, PHP & MySQL
  • JavaScript Color Picker Chrome Extension
  • To Do List Using PHP and MySQL
  • How to Create JavaScript Accordion
  • Ajax File Upload – Without Refreshing Page
  • JavaScript Password Strength Checker
  • How to Download and Install Node.js on Windows with NPM
  • Home
  • About Us
  • Privacy Policy
  • Disclaimer
  • Terms & Conditions
  • Sitemap
  • Contact Us

Copyright © 2023 CodingStatus - All Rights Reserved