What are the best practices for implementing checkbox-based deletion functionality in PHP scripts?
When implementing checkbox-based deletion functionality in PHP scripts, it is important to securely handle user input to prevent SQL injection attacks. One common approach is to use prepared statements with parameterized queries to sanitize input data. Additionally, it is recommended to validate the input data to ensure only expected values are processed.
// Example PHP code snippet for implementing checkbox-based deletion functionality
// Assume the checkboxes are named 'delete[]' in the HTML form
// Check if form is submitted
if(isset($_POST['submit'])){
// Check if any checkboxes are selected
if(isset($_POST['delete'])){
// Connect to database
$conn = new mysqli('localhost', 'username', 'password', 'database');
// Prepare a delete statement
$stmt = $conn->prepare("DELETE FROM table_name WHERE id = ?");
// Bind parameters
$stmt->bind_param("i", $id);
// Loop through selected checkboxes
foreach($_POST['delete'] as $checkbox){
$id = $checkbox;
// Execute the delete statement
$stmt->execute();
}
// Close statement and connection
$stmt->close();
$conn->close();
// Redirect to the same page or a success page
header('Location: success.php');
exit;
}
}