Skylight_lady Posted August 23, 2012 Share Posted August 23, 2012 Hi Guys, here is a problem i have with deleting a file(s) via a cron job. Now i have written a code which deleted all files in a directory .... but it's not what i want. i want to delete one or more files that all have the same value in the database table with an value of delete eg: $query = "SELECT * FROM files_uploaded WHERE file_id = 'delete'"; As my previous code deleted all files in a directory, i have now changed the code to below, but this only deletes one file and not two or more even tho they have the same file_id in the database. $address = '/home/www/mydir/files-uploaded/'; $file = $file_name; if (is_file($address.$file)) { unlink($address.$file); } In the code above the $file_name value is not being shown to you but is stored in the database and displays correctly. How do i get this to delete one or more files depending on the file_id in the database? Link to comment https://forums.phpfreaks.com/topic/267483-unlink-to-delete-1-or-more-files-and-not-all-files/ Share on other sites More sharing options...
Psycho Posted August 23, 2012 Share Posted August 23, 2012 If you have a query that is selecting the files you want to delete, then just iterate over the results of the query and delete those files. //Query the file name for those to be deleted $query = "SELECT file_name FROM files_uploaded WHERE file_id = 'delete'"; $result = mysql_query($query); //Set path to the files if not included in the DB results $path = '/home/www/mydir/files-uploaded/'; //Loop through the results and delete teh files while($row = mysql_fetch_assoc($result)) { $file = $address . $row['file_name']; if (is_file($file)) {unlink($file); } } Just replace "file_name" in the two places above with the appropriate field name in your table. Link to comment https://forums.phpfreaks.com/topic/267483-unlink-to-delete-1-or-more-files-and-not-all-files/#findComment-1371811 Share on other sites More sharing options...
ManiacDan Posted August 23, 2012 Share Posted August 23, 2012 Psycho's code is correct. If that's not what your code looks like, show us the full block like that. Link to comment https://forums.phpfreaks.com/topic/267483-unlink-to-delete-1-or-more-files-and-not-all-files/#findComment-1371812 Share on other sites More sharing options...
Skylight_lady Posted August 23, 2012 Author Share Posted August 23, 2012 Thanks for that. My code is very similar. The problem i had was that i accidently had "die" at the end of the code which terminated the program after the first file was deleted Link to comment https://forums.phpfreaks.com/topic/267483-unlink-to-delete-1-or-more-files-and-not-all-files/#findComment-1371816 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.