Batch delete in php
In PHP applications, operating databases is a common task. There are many situations where we need to delete multiple data rows in the database. This is batch deletion. In this article, I will show you how to implement bulk delete operations in PHP.
- Connect to the database
First, we need to connect to the database. Use the following function:
$conn = mysqli_connect("localhost", "my_user", "my_password", "my_db");
This will connect to the database named "my_db". You need to change it to your own database name and provide the correct username and password.
- Get the selected data rows
Before batch deletion, we need to get the user-selected data rows. For this process we need to use an HTML form and some JavaScript code.
The following is a sample HTML form:
<form method="post" id="deleteForm"> <table> <thead> <tr> <th>ID</th> <th>Name</th> <th>Delete</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>John</td> <td><input type="checkbox" name="ids[]" value="1"></td> </tr> <tr> <td>2</td> <td>Jane</td> <td><input type="checkbox" name="ids[]" value="2"></td> </tr> <tr> <td>3</td> <td>Bob</td> <td><input type="checkbox" name="ids[]" value="3"></td> </tr> </tbody> </table> <button type="submit">Delete</button> </form>
This form has a column of checkboxes, each with a unique value (row ID). When the user selects rows of data to be deleted, the IDs of those rows are added to a form element named "ids[]". The name is an array because we will be selecting multiple values.
Now, we need to write some JavaScript code to get the value selected by the user and pass it to the PHP script behind the scenes.
document.getElementById('deleteForm').addEventListener('submit', function(event) { event.preventDefault(); var selected = document.getElementsByName('ids[]'); var ids = []; for (var i = 0; i < selected.length; i++) { if (selected[i].checked) { ids.push(selected[i].value); } } // Send selected ids to PHP script for processing var request = new XMLHttpRequest(); request.open('POST', 'delete.php', true); request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); request.onload = function() { if (request.status >= 200 && request.status < 400) { // Success console.log(request.responseText); } else { // Error console.log('Error'); } }; request.onerror = function() { // Connection error console.log('Connection Error'); }; request.send('ids=' + JSON.stringify(ids)); });
This code sets up a "submit" event listener that will run when the user clicks the "Delete" button. First, it gets all checkboxes named "ids[]". Next, it creates an array containing the row IDs selected by the user. It then uses AJAX to send the array of identifiers to a PHP script named "delete.php". Finally, when the script returns a response, it prints the response content on the console.
- Handling delete requests
Now, we need to write PHP code to handle the request. In our JavaScript code above, we send the array of identifiers to the script as a JSON string. In PHP, we can use the following code to decode a JSON string into a PHP array:
$ids = json_decode($_POST['ids']);
Next, we need to use a loop to delete each data row:
foreach ($ids as $id) { $sql = "DELETE FROM users WHERE id=$id"; mysqli_query($conn, $sql); }
This loop iterates through for each ID, and use a SQL query to delete the corresponding rows from the "users" table.
- Full code example
The following is the complete PHP script:
In this script, we first connect to the database and then we will Character array is decoded into a PHP array. Next, we use a loop to delete each data row. Finally, we output a success message.
- Summary
In this article, we learned how to implement batch deletion operations in PHP. We use an HTML form and JavaScript code to get the row of data selected by the user, and then use PHP code to handle the request. Bulk deletion is often a necessary feature, and in PHP applications you can easily implement it using the techniques we've covered.
The above is the detailed content of Batch delete in php. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

The article discusses symmetric and asymmetric encryption in PHP, comparing their suitability, performance, and security differences. Symmetric encryption is faster and suited for bulk data, while asymmetric is used for secure key exchange.

The article discusses implementing robust authentication and authorization in PHP to prevent unauthorized access, detailing best practices and recommending security-enhancing tools.

Article discusses retrieving data from databases using PHP, covering steps, security measures, optimization techniques, and common errors with solutions.Character count: 159

The article discusses strategies to prevent CSRF attacks in PHP, including using CSRF tokens, Same-Site cookies, and proper session management.

Prepared statements in PHP enhance database security and efficiency by preventing SQL injection and improving query performance through compilation and reuse.Character count: 159
