Reputation: 57
I am using PHP and MySQL to create a drop box system. The problem I am facing is that I need to delete a folder and delete all the folders and files inside it. It works fine with two folders but when I have 3 folders it does not delete them. Below is the code in PHP. please help me.
<?php
session_start();
require 'connection.php';
$folderid = $_GET['folderid'];
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir")
rrmdir($dir."/".$object);
else unlink ($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
$delete = mysql_query("DELETE FROM file WHERE id='$folderid'");
}
if($folderid != ""){
$result = mysql_query("SELECT file.path FROM ftpdb.file WHERE ftpdb.file.fileID = $folderid");
$qry = mysql_fetch_assoc($result);
$dir = $qry['path'];
//Calls a function which deletes all the files and folder in a pathy specified above
rrmdir($dir);
//Delete From database files and folders if the folderID is not null
$delete = mysql_query("DELETE FROM file WHERE fileID='$folderid' OR parentFolder = '$folderid'");
$deleteFiles = mysql_query("DELETE FROM file_files WHERE folder_id = '$folderid'");
$_SESSION['error'] = "Folder has been deleted";
header("location: client.php");
}else{
$_SESSION['error'] = "Error occured please try again";
header("location: client.php");
}
?>
This is the database I have managed to delete test folder when I delete home but not testing which is in tests. I think that the sql statement is incorrect
Upvotes: 0
Views: 85
Reputation: 31305
You only have one value of $folderid
. Imagine if rrmdir
recurses very deep, removing lots of folders. You cannot catch them all by removing $folderid
and things with $folderid
as the parent. That only goes one level deep!
Your SQL code will need to go inside rrmdir
, so that you can also remove things from the database recursively.
Then to remove all the folders you will either need to:
rrmdir
.)I also note that your last record has two slashes at //testing
. This will make it harder to find a match by path! I would recommend flattening paths like that before they enter the database!
I am also thinking of making my own Dropbox, but I was planning to use something like unison, driven by a couple of shellscripts.
Upvotes: 0
Reputation: 20244
I am sure you would want to find it out by yourself. So let me just provide you with an appropriate google link: https://www.google.de/search?q=mysql+recursion
If you want to know how to convert an arbitrarily sophisticated select statement into a delete statement:
DELETE FROM table WHERE id IN (SELECT id FROM table)
Upvotes: 1
Reputation: 3427
Try this
$result = mysql_query("SELECT file.path FROM ftpdb.file WHERE ftpdb.file.fileID ='$folderid'");
Upvotes: 0