You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

删除评论后如何根据文章ID重定向回对应单篇文章页面

问题分析与解决方案

核心问题

你当前的删除请求只传递了review_id(通过delete参数),但处理删除逻辑时需要的$list_id并没有随请求一起传递到后端。虽然页面渲染时$list_id有值,但当用户点击删除链接发起新的GET请求时,这个变量在后端的上下文里已经不存在了,所以重定向时无法带上该值。

修复方案

方案1:在删除链接中携带list_id参数

修改删除按钮的链接,把list_id作为GET参数一起传递:

<a href="single-property1.php?delete=<?php echo $review_id; ?>&list_id=<?php echo $list_id; ?>" class="mb-0 text-heading border-left border-dark hover-primary lh-1 ml-2 pl-2"><?php echo $list_id; ?> Delete</a>

然后在删除逻辑中,从$_GET获取list_id并做合法性校验:

if (isset($_GET['delete'])) {
    $delete_post_id = $_GET['delete'];
    // 获取传递过来的list_id
    $list_id = $_GET['list_id'];
    
    // 验证参数合法性,防止非法请求
    if (!is_numeric($list_id) || !is_numeric($delete_post_id)) {
        header("location: error.php");
        exit;
    }

    // 用预处理语句防止SQL注入
    $query = "DELETE FROM reviews WHERE review_id = ?";
    $stmt = mysqli_prepare($connection, $query);
    mysqli_stmt_bind_param($stmt, "i", $delete_post_id);
    mysqli_stmt_execute($stmt);
    
    if (mysqli_stmt_affected_rows($stmt) > 0) {
        header("location: single-property1.php?p_id=" . urlencode($list_id));
        exit;
    } else {
        die("删除失败:" . mysqli_error($connection));
    }
}

方案2:从数据库查询对应list_id(更安全)

如果不想在前端暴露list_id,可以在删除前根据review_id从reviews表中查询关联的文章ID(假设表中有存储关联字段,比如property_id):

if (isset($_GET['delete'])) {
    $delete_post_id = $_GET['delete'];
    
    // 先查询对应的文章ID
    $query = "SELECT property_id FROM reviews WHERE review_id = ?";
    $stmt = mysqli_prepare($connection, $query);
    mysqli_stmt_bind_param($stmt, "i", $delete_post_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $row = mysqli_fetch_assoc($result);
    
    if (!$row) {
        // 找不到对应评论,跳转到错误页
        header("location: error.php");
        exit;
    }
    $list_id = $row['property_id'];

    // 执行删除操作
    $delete_query = "DELETE FROM reviews WHERE review_id = ?";
    $stmt = mysqli_prepare($connection, $delete_query);
    mysqli_stmt_bind_param($stmt, "i", $delete_post_id);
    mysqli_stmt_execute($stmt);
    
    if (mysqli_stmt_affected_rows($stmt) > 0) {
        header("location: single-property1.php?p_id=" . urlencode($list_id));
        exit;
    } else {
        die("删除失败:" . mysqli_error($connection));
    }
}

额外注意事项

  • SQL注入防护:原代码直接将$_GET['delete']拼入SQL语句,存在严重注入风险,必须改用预处理语句。
  • 重定向后终止代码:调用header("location: ...")后必须加exit;,避免后续代码继续执行。
  • 权限校验:建议增加用户权限验证,确保只有有权限的用户才能执行删除操作。

内容的提问来源于stack exchange,提问作者Dennis Silas Mbagwu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 13:01:01