即使所需的值不存在,我的php的if语句也会通过
问题描述:
I'm trying to create a reservation system that goes from 8AM to 4PM and I've deliberately set my most recent date on the database to: 2016-04-23 17:50:00 which would translate to an hour of 5 and a minute of 50 but somehow even if my if statement only accepts 8,9,10,11,1,2,3 values for an hour, it still manages to enter with an hour of 5.
My code is:
$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";
}
I tried troubleshooting it by placing echoes to determine until where my ifs are being penetrated and here's the result:
Hour is: 5
Minute is: 50
Minute before adding ten is: 50
New Minute is: 60
Wtf, why did it go here?
(I unfortunately can't post a pic since I'm a new user)
答
if ($hour == "8" || "9" || "10" || "11" || "1" || "2" || "3")
should be
if ($hour == "8" || $hour == "9" || $hour == "10" || $hour == "11" || $hour == "1" || $hour == "2" || $hour == "3")
And similarly everywhere else.
The string "9" will evaluate as boolean 'true', so ($hour=="8" || "9") is the same as writing ($hour == "8" || true ) - or just "true".