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

当state参数无数据库结果时,如何重定向至无参usa.php?

解决方案

你需要先验证传入的state值是否在数据库中存在,若不存在则直接重定向到无参数的usa.php页面,同时可以优化原代码的冗余逻辑,避免重复编写相同的查询语句。

修改后的完整代码

// 提取重复的基础查询条件,减少代码冗余
$baseWhere = "deleted='0' AND filename<>''";

// 获取并过滤URL中的state参数
$getstate = isset($_GET['state']) ? htmlspecialchars($_GET['state']) : '';

// 验证state是否存在,不存在则重定向
if (!empty($getstate)) {
    // 查询该state是否有匹配的有效记录
    $checkStateStmt = $conn->prepare("SELECT COUNT(*) FROM usa WHERE {$baseWhere} AND state=?");
    $checkStateStmt->execute([$getstate]);
    $stateHasRecords = $checkStateStmt->fetchColumn() > 0;

    // 无匹配记录时重定向到无参数页面
    if (!$stateHasRecords) {
        header("Location: usa.php");
        exit; // 必须终止后续代码执行,防止页面继续加载原逻辑
    }
}

// 构建并执行数据查询
$query = "SELECT * FROM usa WHERE {$baseWhere}" . (!empty($getstate) ? " AND state=?" : "");
$stmt = $conn->prepare($query);
!empty($getstate) ? $stmt->execute([$getstate]) : $stmt->execute([]);

// 构建并执行计数查询
$countQuery = "SELECT COUNT(*) FROM usa WHERE {$baseWhere}" . (!empty($getstate) ? " AND state=?" : "");
$stmtcounterview = $conn->prepare($countQuery);
!empty($getstate) ? $stmtcounterview->execute([$getstate]) : $stmtcounterview->execute([]);
$countview = $stmtcounterview->fetchColumn();

关键说明

  • state存在性验证:在执行数据查询前,先通过COUNT(*)判断传入的state是否对应有效记录,计数为0时触发重定向。
  • 重定向处理:使用header("Location: usa.php")完成跳转,必须搭配exit终止后续代码,避免页面继续执行原逻辑。
  • 代码优化:将重复的查询条件提取为$baseWhere变量,减少冗余代码,提升维护性。

内容的提问来源于stack exchange,提问作者Chetan Soni

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 15:47:19