通过数据库和目录删除图像

时间:2013-01-23 14:13:52

标签: php html mysql

有人可以帮我处理我的代码。我可以删除数据库中的图像,但在目录中我不能删除。我试了很长时间,但似乎根本不起作用。有人会帮我吗?这是我的代码:这是图像的代码

<?
//this is were images displayed
                    $query = "SELECT * FROM images WHERE category='home'";
                    $result = mysql_query($query) or die(mysql_error());
                    while($row = mysql_fetch_array($result)){
                    ?>
                    <a href="edithomephotos.php?delete=<?=$row['imageID']?>" onclick = "return confirm('Are you sure you want to delete?')"><img src="images/template/delete.png" id="AEDbutton"></a>


                    echo "<img border=\"0\" src=\"".$row['image']."\" width=\"200\"  height=\"100\">";
                    echo "<br>";                }   


?>

include('global.php');

//this is were image were deleted

if($delete != "") 



    {

        $query = "DELETE FROM images WHERE imageID='".$delete."'";
        ExecuteQuery($query);   

}

//but in here , it cannot delete image through directory
           $query = "SELECT * FROM images WHERE imageID='".$delete."'";

                $result = mysql_query($query);

while ($delete = mysql_fetch_array($result)) {
                $image = $delete['image'];

                 $file= '/.directory/'.$image;

                        unlink($file);


    }



?>

3 个答案:

答案 0 :(得分:2)

您已经删除了表格中的图像条目,之后您尝试在DB中获取相同的条目。所以,首先你可以删除表格中的图像,然后你可以在表格中删除。

<?php
    include('global.php');

    if($delete != "") {
        $query = "SELECT * FROM images WHERE imageID='".$delete."'";
        $result = mysql_query($query);

        while ($delete = mysql_fetch_array($result)) {
            $image = $delete['image'];
            $file= '/.directory/'.$image;
            unlink($file);
        }

        $query = "DELETE FROM images WHERE imageID='".$delete."'";
        ExecuteQuery($query);   
    }
?>

注意: 确保您的路径$file= '/.directory/'.$image;正确,我认为它是从根目录引用的。

答案 1 :(得分:1)

有趣。那是因为您首先从数据库中删除图像ID,然后您尝试获取先前删除的图像的ID(不再存在)并删除与其关联的文件。像这样切换代码。

include('global.php');

if($delete != "") 
{
//first delete the file
$query = "SELECT * FROM images WHERE imageID='".$delete."'";

$result = mysql_query($query);

while ($delete = mysql_fetch_array($result))
{
    try
    {
        $image = $delete['image'];
        $file= '/images/'.$image;
        unlink($file);
    } catch (Exception $e) {

    }
}

// after that delete the id from the db of that image associated with the deleted file
$query = "DELETE FROM images WHERE imageID='".$delete."'";
ExecuteQuery($query);   
}

更新:我添加了try catch

答案 2 :(得分:0)

如果要删除图像,首先需要删除图像,然后在DB中删除