Reputation: 41
I wanna delete the file from the uploads folder before deleting the row data from the database. I used the below code but its giving the error. Error=> No such file or directory
function deleteItem($conn,$product_id)
{
$stmtgetfile=$conn->prepare("SELECT * FROM tbl_item WHERE product_id=:product_id");
$stmtgetfile->bindParam('product_id',$product_id);
$stmtgetfile->execute();
$row = $stmtgetfile->fetch(PDO::FETCH_ASSOC);
$item=$row['product_photo'];
$path="../uploads/".$item;
unlink($path);
// $stmtdelete=$conn->prepare("DELETE FROM tbl_item WHERE product_id=:product_id");
// $stmtdelete->bindParam('product_id',$product_id);
// if($stmtdelete->execute())
// return true;
// return false;
}
Upvotes: 0
Views: 82
Reputation: 28834
You will need to fix the $path
value to get actual path. You can use __DIR__
constant for the same. And, also use file_exists()
function to check if the file actually exists or not, before trying to delete it. It seems that some of the file path(s) in your database are non-existent now.
$path = __DIR__ . "/../uploads/" . $item;
if (file_exists($path)) {
unlink($path);
}
Also, if you are just going to need product_photo
column value, don't use Select *
. Change prepare query statement to:
$stmtgetfile=$conn->prepare("SELECT product_photo FROM tbl_item
WHERE product_id=:product_id");
Do read: Why is SELECT * considered harmful?
Upvotes: 1
Reputation: 127
USE $_SERVER['DOCUMENT_ROOT']
to get absolute path of root directory.
$path=$_SERVER['DOCUMENT_ROOT']."/uploads/".$item;
if(file_exists($path)){
unlink($path);
}else{
echo $path; // check path here
}
Upvotes: 1