从已过期的行中删除图像

时间:2017-02-01 19:48:27

标签: php mysql sql mysqli unlink

嘿,我有一个PHP代码,用于检查哪些行日期已过期并删除它们,其中一列是通过ftp上传到服务器的图像名称,当我删除所有过期记录时我也想删除图像附在他们身上。 我在php上阅读了关于unlink命令但是我没有看到如何将它同时应用于所有图像。

我有这个代码,我只是絮絮叨叨,例如因为我真的不知道该怎么做..

     $sql = "DELETE FROM table WHERE date < NOW()";
 mysqli_query($conn,$sql);

$file = "public_html/images/".//Here should go the image name;
unlink($file);
if($sql)
{
    echo "Records were deleted";
}
?>

有谁能告诉我如何删除附加到已删除行的所有图像?

1 个答案:

答案 0 :(得分:1)

如果要从数据库中的表中删除行,同时从保留它们的服务器上的文件夹中删除图像,则必须一次处理一个删除候选项,以便你可以从行中获取文件名,以便在删除行的同时完成文件删除。

// connect to database

$base_path = 'public_html/images/';
$del_count = 0;

// SELECT all the delete candidates
$sql = "SELECT id,image FROM table WHERE date < NOW()";
$sel4del = mysqli_query($conn,$sql);
if ( ! $sel4del ) {
    echo $sel4del->error;
    exit;
}

// prepare a delete by id
$sql = 'DELETE FROM table WHERE id = ?';
$delrow = mysqli_prepare($conn,$sql);
if ( ! $delrow ) {
    echo $delrow->error;
    exit;
}

// Process all the delete candidates one by one
while ($row = $sel4del->fetch_object() ) {
    // remove the file from disk
    unlink($base_path . $row->image);
    $del_count++;

    // bind the current id to the prepared delete query
    $delrow->bind_param('i', $row->id);    

    // execute the delete of this one row
    $delrow->execute();
}
echo 'images removed = ' . $del_count
?>