我需要使用PHP和MySQL按照day and date
从数据库中获取数据。我在解释下面的表格。
db_day:
day_id day_name
1 Monday
2 Tuesday
3 Wednsday
4 Thursday
5 Friday
6 Saturday
7 Sunday
以上是我的日历表。
db_special:
id restname date_from date_to day_from day_to
1 aaa 2016-09-22 2016-09-26 1 4
2 bbb 2016-10-19 2016-10-28 2 5
3 ccc 2016-10-18 2016-10-25 4 7
以上是我的两张桌子。假设用户输入Tuesday
并且需要从上表中获取日期范围内的值。如果用户仅输入Tuesday
,则首先应计算日期和日期。如果假设今天的日期为Friday
,则会考虑下一个Tuesday
以后。
此处用户输入仅为Tuesday
,因此它将计算今天的日期e.g-2016-10-21
,然后将从上表中过滤值。根据此示例的预期结果应该是表中的这一行:
bbb 2016-10-19 2016-10-28 2 5
我需要此查询来解决此问题。
答案 0 :(得分:0)
您可以尝试使用以下代码:
// $db is PDO instance
// $userDay is user input day
$todayDayId = date('N');
$stmt = $db->prepare('SELECT day_id FROM db_day WHERE day_name=:userDay');
$stmt->execute([':userDay' => $userDay]);
$userDayId = $stmt->fetchColumn();
if($todayDayId > $userDayId) {
$diff = (7-$todayDayId) + $userDayId;
}
else {
$diff = $userDayId - $todayDayId;
}
$wantedDate = date('Y-m-d', strtotime('+'.$diff.' day'));
$pdoData = [
':wantedDate' => $wantedDate,
':wantedDate2' => $wantedDate,
];
$stmt = $db->prepare('SELECT id, restname, date_from, date_to, day_from, day_to
FROM db_special
WHERE date_from>=:wantedDate AND date_to<=:wantedDate2');
$stmt->execute($pdoData);
$result = $stmt->fetchColumn();