The problem with your original code snippet is that you delete the category first, and then attempt to delete the records from that category. If the record deletion or file deletion fails, then you have orphaned records - records belonging to a category that no longer exists.
devinemke's version has that same problem, but it introduces the idea of deleting only those records which had their corresponding files successfully deleted. This is inefficient compared to my method, assuming that there are no file deletion errors.
My method attempts to delete the files first, and then the records of the given category, and then the category itself. This avoids orphaned records, but introduces another problem - if there's an error with file deletion, then one will have records that point to non-existent files.
My reasoning for a solution is this: we want to delete as many records as possible, but at the same time ensure that for every record deleted, there is one (and only one) file deleted. If any file/record is not deleted, we do not want to delete the category.
function deleteCategory($category) {
$result = mysql_query("SELECT id, downfile from gallery_db WHERE category='$category'")
OR die(mysql_error());
$unlink_error = false;
if (mysql_num_rows($result) > 0) {
$del_ids = array();
while ($row = mysql_fetch_assoc($result)) {
if (unlink('/path/to/images/' . $row['downfile'])) {
$del_ids[] = $row['id'];
} else {
$unlink_error = true;
}
}
mysql_query("DELETE FROM gallery_db WHERE id IN (" . implode(',', $del_ids) . ")")
OR die(mysql_error());
}
if (!$unlink_error()) {
mysql_query("DELETE FROM galleryCategory_db WHERE category='$category'")
OR die(mysql_error());
}
}