[英]How to filter day and date from database using PHP and MySQL
I need to fetch day and date from database using PHP and MySQL.我需要使用 PHP 和 MySQL 从数据库中获取日期和日期。 My table is below:
我的表如下:
db_day: db_day:
day_id day_name
1 Monday
2 Tuesday
3 Wednsday
4 Thursday
5 Friday
6 Saturday
7 Sunday
The above is my day table.上面是我的一天表。
db_special: 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
The above are my two table.以上是我的两张表。 Suppose user has the input
Tuesday
and it need to be fetched the value within date range from the above table.Here if user has the input only Tuesday
,first it should calculate the day and date.假设用户有
Tuesday
的输入,需要从上表中获取日期范围内的值。这里如果用户只有Tuesday
的输入,首先应该计算日期和日期。 If suppose today's day is Friday
it will consider next Tuesday
onwards.如果假设今天是
Friday
,它将从下Tuesday
开始考虑。
Here user input is only Tuesday
so it will calculate today's date eg-2016-10-21
and then will filter value from the above table.此处用户输入仅是
Tuesday
因此它将计算今天的日期eg-2016-10-21
,然后将从上表中过滤值。 The expected result as per this example should be this row from the table:根据此示例的预期结果应该是表中的这一行:
bbb 2016-10-19 2016-10-28 2 5
How can I write the query to resolve this problem?如何编写查询来解决此问题?
You can try with this code:您可以尝试使用以下代码:
// $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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.