What is the best practice for deleting entries from a database that may have associated images in PHP?
When deleting entries from a database that may have associated images, it is important to first delete the images before deleting the database entry to avoid orphaned image files. One way to achieve this is by querying the database to get the image filenames associated with the entry, deleting the images from the server, and then deleting the entry from the database.
<?php
// Connect to database
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');
// Get image filenames associated with the entry
$stmt = $pdo->prepare("SELECT image_filename FROM images WHERE entry_id = :entry_id");
$stmt->bindParam(':entry_id', $entry_id);
$stmt->execute();
$images = $stmt->fetchAll(PDO::FETCH_COLUMN);
// Delete images from server
foreach ($images as $image) {
unlink('path/to/image/directory/' . $image);
}
// Delete entry from database
$stmt = $pdo->prepare("DELETE FROM entries WHERE id = :entry_id");
$stmt->bindParam(':entry_id', $entry_id);
$stmt->execute();
?>