我试图根据我的数据库中的开启和关闭时间来显示商店是打开还是关闭。如果是打开则显示当天的开启和关闭时间,如果是关闭回声关闭。我的问题是,即使商店计划开放(尝试1)或者根本没有回应任何东西(尝试2),我的查询也会回复关闭。
我的数据库中的已关闭商店表示为00:00。 任何建议或指导都会非常感激,因为我在教自己并且已经停下来了。
DB
CREATE TABLE `Opening_hrs` (
`OH_ID` bigint(255) NOT NULL AUTO_INCREMENT,
`Restaurant_ID` bigint(255) NOT NULL,
`Day_of_week` int(11) NOT NULL,
`Open_time` time NOT NULL,
`Closing_time` time NOT NULL,
PRIMARY KEY (`OH_ID`),
KEY `Restaurant_ID` (`Restaurant_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8
这是我的第一次尝试
date_default_timezone_set("Europe/London");
$output_ohr = '';
$ohrs = mysqli_query($dbc, "SELECT * FROM Opening_hrs
WHERE Restaurant_ID='$rest_id' AND Day_of_week = DATE_FORMAT(NOW(), '%w')
AND CURTIME() BETWEEN Open_time AND Closing_time");
echo var_dump($ohrs);
$count_ohrs = mysqli_num_rows($ohrs);
if ($count_ohrs === 0) {
$output_ohr = '<b> Closed</b>';
} else {
$i = 1;
}while ($row_ohr = mysqli_fetch_array($ohrs )) {
$o_time = $row_ohr['Open_time'];
$c_time = $row_ohr['Closing_time'];
$output_ohr = $output_ohr . '<p>Open</p>' .
'<p>' .$o_time. ' - ' .$c_time. '</p>'
;
$i++;
}
我的第二次尝试
date_default_timezone_set("Europe/London");
$closed= strtotime("00:00am today GMT");
$output_ohr = '';
$ohrs = mysqli_query($dbc, "SELECT * FROM Opening_hrs
WHERE Restaurant_ID='$rest_id' AND Day_of_week = DATE_FORMAT(NOW(), '%w')
AND CURTIME() BETWEEN Open_time AND Closing_time");
echo var_dump($ohrs);
$i = 1;
while ($row_ohr = mysqli_fetch_array($ohrs )) {
$o_time = $row_ohr['Open_time'];
$c_time = $row_ohr['Closing_time'];
if($o_time === $closed){
$output_ohr = '<p>closed</p>';
}else{
$output_ohr = $output_ohr . '<p>Open</p>' .
'<p>' .$o_time. ' - ' .$c_time. '</p>'
;
$i++;
}
}
答案 0 :(得分:0)
在您的第二次尝试中,您只选择开放的商店。如果商店关闭,查询将不会返回任何行,因此while
块甚至不会运行一次。
使用以下代码查看商店是开放还是关闭:
$stmt = mysqli_prepare($dbc, "SELECT COUNT(*) FROM Opening_hrs
WHERE Restaurant_ID=? AND Day_of_week = DATE_FORMAT(NOW(), '%w')
AND CURTIME() BETWEEN Open_time AND Closing_time");
$stmt->bind_param('i', $rest_id);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
if ($result) {
echo 'Open';
} else {
echo 'Closed';
}
(注意使用prepared statements阻止可能的SQL注入。)