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.
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
You should also learn the following examples –
Check Uncheck All checkboxes with a single checkbox using-jquery
Integrate Google ReCAPTCHA using PHP
Create Admin Panel Template in PHP
First of all, create the following folder structure –
myproject/ |__backend.php |__custom.js |__rocords-table.html
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. Delete Multiple Records script
The code handles the deletion of selected records from a ‘developers’ table in a database based on posted IDs, and it also fetches and displays data from the table.
File 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"; } } ?>
Explanation –
- The code includes a database connection file and checks if the POST parameters ‘checkedId’ and ‘deleteAll’ are set.
- If set, it retrieves the ‘checkedId’ array from POST and calls a function ‘deleteMultipleData’ to delete multiple records from the database using the provided IDs.
- The code then fetches data from the ‘developers’ table sorted by ID in descending order using the ‘fetch_data’ function.
- The ‘fetch_data’ function executes a SELECT query and returns an array of associative arrays containing the fetched data.
- The ‘deleteMultipleData’ function takes a database connection and an array of IDs, implodes the IDs to create a comma-separated string and deletes records from the ‘developers’ table with matching IDs.
- If the deletion is successful, it returns a success message.
3. Display Multiple records with checkboxes
The HTML document includes a form with a table displaying records fetched from a database. It provides checkboxes for each record, a “Check All” option, and a “Delete All” button. The backend PHP file handles database operations, and success/failure messages are displayed at the top of the page. Styling is done using Bootstrap, and jQuery is included for additional functionality.
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>
Explanation –
- The code includes a backend PHP file that handles database operations.
- The HTML document uses Bootstrap for styling and includes jQuery and a custom JavaScript file.
- It displays a form with a table containing records fetched from the database, along with checkboxes for each record.
- If records exist, it populates the table rows with data, including a checkbox for each record.
- A “Check All” checkbox allows selecting all records, and a “Delete All” button triggers the deletion of selected records.
- The backend operation result (success or failure message) is displayed at the top of the page.
4. Select Multiple records with checkboxes
The jQuery code ensures the document is ready and sets up checkbox behavior for checking/unchecking all and confirming deletion. If at least one checkbox is selected for deletion, a confirmation prompt appears; otherwise, it alerts to check at least one record and prevents form submission.
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; } }
Explanation –