php - 从服务器文件夹中删除图像

标签 php html mysql

这是在我的 localhost/file/img 文件夹中上传图片并在我的表中插入图片路径和名称的代码。

<?php

if (isset($_POST['submit']))
  {
  $file_id = $_POST['file_id'];
  if (count($_FILES['upload']['name']) > 0)
    {
    for ($i = 0; $i < count($_FILES['upload']['name']); $i++)
      {
      $tmpFilePath = $_FILES['upload']['tmp_name'][$i];
      if ($tmpFilePath != "")
        {
        $shortname = $_FILES['upload']['name'][$i];
        $filePath = "img/" . $_FILES['upload']['name'][$i];
        if (move_uploaded_file($tmpFilePath, $filePath))
          {
          $files[] = $shortname;
          $query = "insert into images(id,img_name) values('$file_id',' $filePath')";
          mysqli_query($con, $query);
          }
        }
      }
    }

  echo "<h1>Uploaded:</h1>";
  if (is_array($files))
    {
    echo "<ul>";
    foreach($files as $file)
      {
      echo "<li>$file</li>";
      }

    echo "</ul>";
    }
  }

?>
具有属性 img_name 类型的

Table ImagesLONGBLOB 现在它完全可以正常工作但是当我从数据库中删除图像时出现找不到图像名称的错误。这是使用 href 发送图像 ID 和图像名称的代码

<ul>
  <a href="index.php?img_id=<?php echo urlencode($id); ?>&img=<?php echo urlencode($img); ?>" 
    style="color:red; margin-left:18px;" onclick="return confirm('Are you sure you want to delete this?')" >Delete
  </a>
</ul>

现在这里是我想要从我的数据库以及我名为 img 的本地主机文件夹中删除的代码。

<?php

if (isset($_GET['img_id'], $_GET['img']))
  {
  $id = $_GET['img_id'];
  $img = $_GET['img'];
  $query = "delete from images where id='$id' and image='$img'";
  if (mysqli_query($con, $query))
    {
    unlink($img);
    echo '<script language="javascript">';
    echo 'alert("Image Deleted successfully")';
    echo '</script>';
    }
    else
    {
    echo '<script language="javascript">';
    echo 'alert("image does not exist")';
    echo '</script>';
    }
  } 
?>

现在显示未找到 img/image_name.jpg 的警告。请帮助我。

最佳答案

我认为你的删除查询是错误的

if(isset($_GET['img_id'] , $_GET['img'])){
$id=$_GET['img_id'];
$img=$_GET['img'];
$query="delete from images where id='$id' and image='$id'";
}

$query="delete from images where id='$id' and image='$img'";

在此查询中,您使用相同的 $id 变量检查 Id 和 Image 字段

关于php - 从服务器文件夹中删除图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48804530/

相关文章:

php - 为什么我的 <body> 内容与外部文件中的内容 "included"重叠?

php - 更改服务器中正在使用的电子邮件地址

mysql - 如何只查询特定的列?

mysql - 查找至少有 2 行的值为 x 的条目

php - undefined variable : data (View: C:\cygwin64\home\hp\AddressBook\resources\views\Update\edit.blade.php)

php: __destruct 问题(OOP 新手)

php - mysqli 使用 while 循环准备语句

html - 更改 SVG 图像在帧内的位置

html - Github页面404找不到文件

javascript - Safari 无法显示动态创建页面的窗口标题