What are some best practices for implementing a delete function in PHP for multiple entries in a database table?
When implementing a delete function for multiple entries in a database table in PHP, it is best practice to use prepared statements to prevent SQL injection attacks. Additionally, it is recommended to validate user input to ensure that only authorized users can delete entries. Lastly, consider implementing a confirmation step to prevent accidental deletions.
<?php
// Assuming $ids is an array of IDs to be deleted
$ids = [1, 2, 3];
// Establish database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare the SQL statement
$stmt = $pdo->prepare("DELETE FROM mytable WHERE id = :id");
// Loop through each ID and execute the delete statement
foreach ($ids as $id) {
$stmt->execute(['id' => $id]);
}
echo "Entries successfully deleted.";
?>