删除数据库中的图像

时间:2014-04-22 13:32:06

标签: php database image

我正在尝试通过PHP删除数据库中的特定图像。

我有一个页面,其中显示了数据库中的所有图像,我想在每个图像下面都有一个按钮,所以我可以通过他们的ID单独删除它们,但我不知道如何。

这是显示所有图像的PHP代码:

<?php
$result = mysqli_query($con, "SELECT * FROM galeria");
?>
<h5>Images:</h5>
<?php
while ($row = mysqli_fetch_array($result)) {
    ?><h6> <?php echo $row['titleimg']; ?></h6>
    <p><?php echo $row['events_id']; ?></p>
    <img src="../images/<?php echo $row["img"]; ?>" width="301px" height="200px"/>
    <form action="delete_images.php" method="post">
        <input type="submit" name="delete" value="Delete" />
    </form>
    <?php
    echo "<br>";
    echo "<br>";
}
?>

现在,我的“delete_images.php”文件中的代码是什么?

2 个答案:

答案 0 :(得分:1)

您的表单需要一条额外的信息,即要删除的图片的标识符。类似的东西:

<form action="delete_images.php" method="post">
    <input type="hidden" name="id" value="<?php echo $row['img_id'] ?>" />
    <input type="submit" name="delete" value="Delete" />
</form>

当然,我猜测列名称(img_id),但该特定图像的任何标识符都可以解决问题。这样,您对delete_images.php的POST将具有该值(在$_POST['id']中),并且可以在对数据库的DELETE查询中使用它。

答案 1 :(得分:0)

放置一个隐藏的输入字段,其中包含要删除的imageName。

<input type="hidden" value="'.$row["img"].'" name="imageName" />

// Now write some server side code in delete_images.php that will delete file 

  if (array_key_exists('imageName', $_POST)) {
  $filename = $_POST['imageName'];
  if (file_exists($filename)) {
   unlink($filename);
  // Write Mysql query that will delete the row from database
  echo 'File '.$filename.' has been deleted';
   } else {
    echo 'Could not delete '.$filename.', file does not exist';
   }
   }
相关问题