简体   繁体   中英

Get date closest to today in PHP from database

UPDATE

I'm making a backend of a website. The mean point of the website is to give a clear overview to the visitors when and what activities we are organizing.
So I filled the database with all kinds of activities. Every activity has a date, a name and some other information.

It's quite obvious the visitors aren't helped by showing the activities in the past, so I only want them to show the forthcoming activities. And to save myself a lot of work, it would be nice to do PHP/MySQL all the work and showing the visitors only the 2 next events.

Can you advise me a MySQL function to do this?

Thanks in advance,

You can use DATEDIFF and ABS ...

SELECT * FROM `activities` ORDER BY ABS(DATEDIFF(NOW(), `date`)) LIMIT 2

From the updated question only future activities are to be considered... So...

SELECT * FROM `activities` WHERE `date` > NOW() ORDER BY `date` LIMIT 2

Just some advice:

Select the closest 2 events before the current moment and the closest 2 after the current moment.

(SELECT *
FROM ...
WHERE `time` < NOW()
ORDER BY `time` DESC
LIMIT 2)
UNION
(SELECT *
FROM ...
WHERE `time` > NOW()
ORDER BY `time` ASC
LIMIT 2)

At this point you'll have at most 4 events in PHP. But you only need 2. The closest 2. To find out which are the closest you make use of strtotime and check the differences between the timestamps of the events and the current timestamp that you can get by calling time() . After that you keep only the 2 closest events.

Note that this can be achieved directly from MySQL, but it's harder that way.


@Latest update. It's sufficient to read this if you don't want to know more.

Just use this query:

SELECT *
FROM ...
WHERE `time` > NOW()
ORDER BY `time` ASC
LIMIT 2
$query = 'SELECT .... FROM ... WHERE `date` > '.$today.' ORDER BY `date` DESC LIMIT 2';

$today取决于您的date列类型。

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