使用prepare statment找不到图像,从服务器取消链接图像

时间:2018-04-20 14:17:09

标签: php mysqli

我遇到显示图片值的问题,但是找不到图像。

我想在删除帖子时删除属于帖子的图片,但图片值会变为emtpy。 需要帮助才能找到我在查询中出错的地方。

我的疑问:

if (isset($_GET['id'])) {

$delete =   $_GET['id']; 
$stmt = $conn->prepare("SELECT image FROM posts WHERE id = ?");
$stmt->bind_param('i', $delete);
$stmt->execute();
$stmt->bind_result($image);
$row = $stmt->fetch();
$stmt->close();

$stmt = $conn->prepare("DELETE FROM posts WHERE id = ?"); 
$stmt->bind_param('i', $delete);
$stmt->execute(); 
$stmt->close();

$filename = '../images/posts/'.$row['image'].'';
  if (file_exists($filename)) {
    unlink($filename);
    echo 'File '.$filename.' has been deleted';
  } else {
    echo 'Could not delete '.$filename.', file does not exist';
  }
}

1 个答案:

答案 0 :(得分:0)

if (isset($_GET['id'])) {

    $delete = $_GET['id']; 
    $stmt = $conn->prepare("SELECT image FROM posts WHERE id = ?");
    $stmt->bind_param('i', $delete);
    $stmt->execute();
    $stmt->bind_result($image);
    $stmt->fetch();
    $stmt->close();

bind_result()

将结果集中的列绑定到变量。

fetch()

将准备好的语句中的结果提取到mysqli_stmt_bind_result()绑定的变量中。

    $filename = '../images/posts/'.$image;
    if (file_exists($filename)) {
      unlink($filename);
      echo 'File '.$filename.' has been deleted';
    } else {
      echo 'Could not delete '.$filename.', file does not exist';
    }
}

您可以使用 var_dump($ image)来检查结果。如果为NULL,则表示未找到任何记录。您可能必须检查$ _GET ['id']的值,或者表中是否存在记录。