简体   繁体   中英

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. My table is below:

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:

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. If suppose today's day is Friday it will consider next Tuesday onwards.

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. 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM