Tonight I was having troubles deleting a file from a directory in an application I am working on. It kept deleting the entry in the table but not the actual file from the directory. Here is what the code looked like:
< ?php
$sql = "DELETE FROM uploads WHERE upload_id = $id";
$result = mysql_query($sql);
//if it ran ok
if (mysql_affected_rows() == 1) {
delete the file from the uploads dir
unlink('uploads/'$row['file_name']);
}
?>
I couldn’t figure out for the life of me then I tried this:
< ?php
//delete the file from the uploads dir
unlink('uploads/' . $row['file_name']);
$sql = "DELETE FROM uploads WHERE upload_id = $id";
$result = mysql_query($sql);
//if it ran ok
if (mysql_affected_rows() == 1) {
//do something
}
?>
It worked perfect! I just had to seperate the name ($row['file_name']), which could also be a variable with a space: ‘uploads/’ . I also had to make sure the unlink was before the DELETE query because if it was after the query it would be trying to delete something that wasn’t there.
Backseat Drivers