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="refresh" content="0;URL=view_links.php">'; } }</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!