Home > Database > Mysql Tutorial > How to Correctly Delete Multiple Database Rows Using Checkboxes in PHP?

How to Correctly Delete Multiple Database Rows Using Checkboxes in PHP?

Mary-Kate Olsen
Release: 2024-12-01 08:20:10
Original
864 people have browsed it

How to Correctly Delete Multiple Database Rows Using Checkboxes in PHP?

Delete Multiple Rows Using Checkboxes in PHP

Selecting and deleting multiple rows from a database table is a common task in web development. In this case, the user has implemented checkboxes to allow users to select specific rows for deletion, but the code is not working as expected.

Key Issue

The primary issue is that the PHP code responsible for deleting the selected rows treats the checkbox values as a single value instead of an array. To resolve this, change the checkbox input tag to:

<input name="checkbox[]" type="checkbox" value="<?php echo $row['link_id']; ?>">
Copy after login
Copy after login

Missing Database Connection

Additionally, the mysqli_query() function requires a database connection as its first argument. In the provided code, the connection is missing. Modify the code to properly include the connection:

$result = mysqli_query($dbc, $sql);
Copy after login
Copy after login

Updated Code

With these modifications, the updated code should look like this:

<input name="checkbox[]" type="checkbox" value="<?php echo $row['link_id']; ?>">
Copy after login
Copy after login
$result = mysqli_query($dbc, $sql);
Copy after login
Copy after login

Explanation

By changing the checkbox name to an array ("checkbox[]"), the code ensures that the checkbox values can be accessed as an array in PHP. When the "Delete" button is clicked, the code iterates through the array and deletes the selected rows one by one using the looped $del_id values. The updated PHP code also correctly passes the database connection to the mysqli_query() function, which is required for the query to execute successfully.

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

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template