Home  >  Article  >  Backend Development  >  How to Delete Multiple Rows Using Checkboxes in PHP: A Debugging Guide

How to Delete Multiple Rows Using Checkboxes in PHP: A Debugging Guide

Patricia Arquette
Patricia ArquetteOriginal
2024-10-27 13:32:02811browse

How to Delete Multiple Rows Using Checkboxes in PHP: A Debugging Guide

Deletion of Multiple Rows via Checkbox Selection in PHP

When facing difficulties in deleting multiple rows from a MySQL database table, it's crucial to scrutinize the PHP code for any potential errors. One common issue arises when trying to select checkboxes for deletion.

Checkbox Selection and Looping

Initially, the PHP code utilized individual checkboxes with distinct names. To address this, we need to treat them as an array using "checkbox[]". This enables us to determine how many checkboxes have been selected and subsequently loop through them for deletion.

Database Connection in Query

An additional error was discovered in the code. The "mysqli_query" function requires two parameters: the database connection and the query string. In the provided code, the database connection was not passed to the query. By adding the database connection parameter, the query can be executed properly.

Optimized Code

The code below incorporates both the array treatment for checkboxes and the inclusion of the database connection in the query:

<code class="php">if(isset($_POST['delete'])) {
  $checkbox = $_POST['checkbox'];
  for($i=0; $i<count($checkbox); $i++) {
    $del_id = $checkbox[$i];
    $sql = "DELETE FROM links WHERE link_id='$del_id'";
    $result = mysqli_query($dbc, $sql);
  }
  if($result){
    echo '<meta http-equiv=&quot;refresh&quot; content=&quot;0;URL=view_links.php&quot;>';
  }
}</code>

By implementing these modifications, you can effectively delete multiple rows from your database table using checkboxes.

The above is the detailed content of How to Delete Multiple Rows Using Checkboxes in PHP: A Debugging Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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