【问题标题】:My php's if statement goes through even if the required value is not present即使所需的值不存在,我的 php 的 if 语句也会通过
【发布时间】:2016-04-22 00:44:52
【问题描述】:

我正在尝试创建一个从早上 8 点到下午 4 点的预订系统,我特意将我在数据库中的最近日期设置为:2016-04-23 17:50:00,这将转换为一个小时5 分钟和 50 分钟,但不知何故,即使我的 if 语句在一个小时内只接受 8,9,10,11,1,2,3 值,它仍然设法以 5 小时输入。

我的代码是:

$get_recent_date = mysqli_fetch_assoc(mysqli_query($con,"SELECT date FROM schedule ORDER BY date desc"));
$get_datetime = new DateTime($get_recent_date['date']);
$date = date_format($get_datetime, 'j'); //numeric date w/o leading zeros
$month = date_format($get_datetime, 'n'); //numeric month w/o leading zeros
$year = date_format($get_datetime, 'Y'); //numeric year w/o leading zeros
$hour = date_format($get_datetime, 'g'); //numeric hour w/o leading zeroes
$minute = date_format($get_datetime, 'i'); //numeric hour w/o leading zeroes

echo "Hour is: "; echo $hour; echo "<br>";
echo "Minute is: "; echo $minute; echo "<br>";

if ($hour == "8" || "9" || "10" || "11" || "1" || "2" || "3")
{
    if($minute == "0" || "00" || "10" || "20" || "30" || "40")
    {
        echo "Minute before adding ten is: "; echo $minute; echo "<br>";
        $minute = $minute + '10';
        echo "New Minute is: "; echo $minute; echo "<br>";
            if($minute == "60")
            {
                echo "Wtf, why did it go here?";
            }
    }

    else if($minute == "50")
    {
        $hour = $hour + '1';
        $minute = "0";

        $date = strtotime($date);
        $hour = strtotime($hour);
        $minute = strtotime($minute);
        echo $date; echo $hour; echo $minute;
        $got_datetime = date_create_from_format('j-n-Y-g-i', "$date-$month-$year-$hour-$minute");
        mysqli_query($con,"INSERT INTO schedule (date) VALUES ($got_datetime)");
    }

    else
    {
        echo "Minute is incorrect";
    }

}


else {
    echo "Hour is incorrect";
}

我尝试通过放置回声来对其进行故障排除,以确定我的 ifs 被穿透的位置,结果如下:

Hour is: 5
Minute is: 50
Minute before adding ten is: 50
New Minute is: 60
Wtf, why did it go here? 

(很遗憾,我是新用户,所以无法发布图片)

【问题讨论】:

  • 试试这个:if ($hour == "8" || $hour == "9" || $hour == "10" || $hour == "11" || $hour == "1" || $hour == "2" || $hour == "3")
  • 哦,成功了,谢谢!所以我必须将每个可能的值与变量一一比较。
  • 是的,你必须比较每一个。
  • 您也可以创建一个包含所有值的数组,然后检查该值是否在数组中。 $values = array(1, 2, 3, 8, 9, 10, 11); if (in_array($hour, $values) { /* It's there */ } -- 如果你有很多变量,这会更容易。
  • 哇,谢谢!现在我的代码更干净了。

标签: php if-statement


【解决方案1】:
if ($hour == "8" || "9" || "10" || "11" || "1" || "2" || "3")

应该是

if ($hour == "8" || $hour == "9" || $hour == "10" || $hour == "11" || $hour == "1" || $hour == "2" || $hour == "3")

其他地方也一样。

字符串 "9" 将评估为布尔值 'true',因此 ($hour=="8" || "9") 与编写 ($hour == "8" || true ) 相同 - 或只是“真实”。

【讨论】:

  • 我明白了,谢谢,不仅为此,您还回答了我要问的另一个问题。
猜你喜欢
  • 2023-04-07
  • 2016-11-19
  • 1970-01-01
  • 1970-01-01
  • 2020-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多