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

执行时间查询条件判断时遇问题:始终进入else分支

问题分析与修复方案

你的代码始终进入else分支,主要有两个核心问题:

1. 12小时制字符串的直接比较逻辑错误

你使用date("h:i A")得到的是带AM/PM的12小时制时间字符串(比如10:00 AM、12:00 PM),直接用字符串比较会出现逻辑错误:

  • 例如"12:00 PM"和"01:00 PM",字符串比较时"12"开头的会被判定为大于"01"开头的,但实际时间上中午12点是早于下午1点的,这就导致你的时间判断完全颠倒。

2. 未检查数据库查询是否成功

如果你的SQL查询没有匹配到数据(比如provider_id或day不存在),mysqli_fetch_assoc会返回null,此时$opening_time和$closing_time是未定义的,直接比较必然进入else分支。


修复后的代码

下面是修正后的完整代码,同时加入了SQL注入防护(预处理语句)和错误检查:

date_default_timezone_set('Asia/Kolkata');
$currentDay = date("l");
$response = [];

// 使用预处理语句避免SQL注入
$status = "SELECT opening_time, closing_time FROM nesbaty_working_time WHERE provider_id=? AND day=?";
$stmt = mysqli_prepare($con, $status);
mysqli_stmt_bind_param($stmt, "ss", $r, $currentDay);
mysqli_stmt_execute($stmt);
$qry_res2 = mysqli_stmt_get_result($stmt);

// 检查是否查询到有效数据
if (mysqli_num_rows($qry_res2) > 0) {
    $array1 = mysqli_fetch_assoc($qry_res2);
    $opening_time = $array1['opening_time'];
    $closing_time = $array1['closing_time'];
    
    // 将时间转换为当天的时间戳,确保比较的是同一天的时段
    $currentTimestamp = time();
    $openingTimestamp = strtotime(date("Y-m-d") . " " . $opening_time);
    $closingTimestamp = strtotime(date("Y-m-d") . " " . $closing_time);
    
    // 通过时间戳进行准确的时间比较
    if ($currentTimestamp > $openingTimestamp && $currentTimestamp < $closingTimestamp) {
        $response['status'] = "Open";
    } else {
        $response['status'] = "Close";
    }
} else {
    // 无匹配数据时默认设为关闭,或根据业务需求调整
    $response['status'] = "Close";
}

// 释放资源
mysqli_stmt_close($stmt);

额外调试建议

如果还是有问题,可以在代码中加入调试输出,确认各变量的值是否符合预期:

echo "当前星期:{$currentDay}<br>";
echo "查询到的开门时间:{$opening_time}<br>";
echo "查询到的关门时间:{$closing_time}<br>";
echo "当前时间戳:{$currentTimestamp}<br>";
echo "开门时间戳:{$openingTimestamp}<br>";
echo "关门时间戳:{$closingTimestamp}<br>";

内容的提问来源于stack exchange,提问作者Pravin Suthar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 09:00:13