Home Backend Development PHP Problem Batch delete in php

Batch delete in php

May 07, 2023 pm 12:02 PM

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.

  1. 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");
Copy after login

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.

  1. 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>
Copy after login

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));
});
Copy after login

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.

  1. 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']);
Copy after login

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);
}
Copy after login

This loop iterates through for each ID, and use a SQL query to delete the corresponding rows from the "users" table.

  1. Full code example

The following is the complete PHP script:

Copy after login

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.

  1. 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. Mar 25, 2025 am 10:37 AM

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

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. Mar 26, 2025 pm 04:13 PM

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.

PHP Secure File Uploads: Preventing file-related vulnerabilities. PHP Secure File Uploads: Preventing file-related vulnerabilities. Mar 26, 2025 pm 04:18 PM

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.

PHP Encryption: Symmetric vs. asymmetric encryption. PHP Encryption: Symmetric vs. asymmetric encryption. Mar 25, 2025 pm 03:12 PM

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.

PHP Authentication & Authorization: Secure implementation. PHP Authentication & Authorization: Secure implementation. Mar 25, 2025 pm 03:06 PM

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

How do you retrieve data from a database using PHP? How do you retrieve data from a database using PHP? Mar 20, 2025 pm 04:57 PM

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

PHP CSRF Protection: How to prevent CSRF attacks. PHP CSRF Protection: How to prevent CSRF attacks. Mar 25, 2025 pm 03:05 PM

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

What is the purpose of prepared statements in PHP? What is the purpose of prepared statements in PHP? Mar 20, 2025 pm 04:47 PM

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

See all articles