What is the best practice for selecting multiple entries with checkboxes and deleting them from a MySQL database using PHP?
When selecting multiple entries with checkboxes and deleting them from a MySQL database using PHP, the best practice is to loop through the selected checkboxes and execute a DELETE query for each selected entry. This can be achieved by creating a form with checkboxes for each entry, submitting the form to a PHP script that processes the selected checkboxes and deletes the corresponding entries from the database.
<?php
// Check if form is submitted
if(isset($_POST['delete'])){
// Connect to MySQL database
$conn = new mysqli("localhost", "username", "password", "database");
// Loop through selected checkboxes
foreach($_POST['checkbox'] as $id){
// Sanitize input
$id = $conn->real_escape_string($id);
// Execute DELETE query
$conn->query("DELETE FROM table_name WHERE id = $id");
}
// Close database connection
$conn->close();
}
?>
<form method="post" action="delete.php">
<?php
// Connect to MySQL database
$conn = new mysqli("localhost", "username", "password", "database");
// Retrieve entries from database
$result = $conn->query("SELECT * FROM table_name");
// Display entries with checkboxes
while($row = $result->fetch_assoc()){
echo '<input type="checkbox" name="checkbox[]" value="'.$row['id'].'">'.$row['name'].'<br>';
}
// Close database connection
$conn->close();
?>
<input type="submit" name="delete" value="Delete Selected Entries">
</form>
Keywords
Related Questions
- What potential pitfalls should be considered when upgrading from PHP 7.4 to PHP 8.0, specifically regarding functions like feof()?
- What are some potential pitfalls to be aware of when working with PHP execution paths and environment variables?
- What are the best practices for handling form display within a loop in PHP?