What are the best practices for implementing checkbox functionality in PHP to delete selected data entries from a table?
When implementing checkbox functionality in PHP to delete selected data entries from a table, you should first create checkboxes next to each data entry that the user can select. Upon form submission, you should check which checkboxes are selected and then delete the corresponding data entries from the database. Make sure to sanitize user input to prevent SQL injection attacks.
// Assuming you have a table named 'entries' with columns 'id' and 'data'
// Display checkboxes next to each data entry
$query = "SELECT * FROM entries";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($result)) {
echo "<input type='checkbox' name='delete[]' value='" . $row['id'] . "'>";
echo $row['data'] . "<br>";
}
// Delete selected data entries upon form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['delete'])) {
foreach($_POST['delete'] as $id) {
$id = mysqli_real_escape_string($connection, $id);
$delete_query = "DELETE FROM entries WHERE id = $id";
mysqli_query($connection, $delete_query);
}
}
}
Keywords
Related Questions
- What steps can be taken to troubleshoot and debug PHP scripts that are encountering issues with reCaptcha validation?
- How can the use of autoloading functions like spl_autoload_register impact the loading of classes from external libraries like phpseclib, and what are alternative approaches to consider?
- What are the potential issues one might face when trying to connect PHP5-CLI with Postgres?