在删除行数据之前先删除文件?

时间:2018-11-07 06:26:12

标签: php mysql delete-file

在从数据库删除行数据之前,我想从上载文件夹中删除文件。我使用下面的代码,但它给出了错误。 错误=>没有这样的文件或目录

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;
}

2 个答案:

答案 0 :(得分:1)

您将需要修复$path值以获得实际路径。您可以使用__DIR__常量。并且,在尝试删除文件之前,还请使用file_exists()函数检查文件是否确实存在。看来数据库中的某些文件路径现在不存在。

$path = __DIR__ . "/../uploads/" . $item;
if (file_exists($path)) {
    unlink($path);
}

此外,如果您只需要product_photo列值,请不要使用Select *。将准备查询语句更改为:

$stmtgetfile=$conn->prepare("SELECT product_photo FROM tbl_item 
                             WHERE product_id=:product_id");

请阅读:Why is SELECT * considered harmful?

答案 1 :(得分:1)

使用$_SERVER['DOCUMENT_ROOT']获取根目录的绝对路径。

$path=$_SERVER['DOCUMENT_ROOT']."/uploads/".$item;
if(file_exists($path)){
   unlink($path);
}else{
   echo $path; // check path here
}
相关问题