I have a Calendar of Events table and I would like to select events with dates equal to or greater than today. When I use the following SELECT statement, it only retrieves e
You are looking for CURDATE():
$db->query("SELECT * FROM events WHERE event_date >= CURDATE()");
Or:
$db->query("SELECT * FROM events WHERE event_date >= CURRENT_DATE()");
Here's the difference between CURDATE and NOW:
mysql> select CURDATE();
+------------+
| CURDATE() |
+------------+
| 2017-03-17 |
+------------+
1 row in set (0.03 sec)
mysql> select NOW();
+---------------------+
| NOW() |
+---------------------+
| 2017-03-17 09:04:45 |
+---------------------+
1 row in set (0.00 sec)
I always use NOW just to be accurate
If you care only about the date, not the time, use CURDATE() instead of NOW()
.
Of course you can alternatively use the synonym CURRENT_DATE
(with or without parentheses after it), but the docs I pointed to give CURDATE
as the first spelling;-).
The reason that this query:
SELECT * FROM events WHERE event_date >= NOW()
...returns records from the future, is because NOW() includes the time as well as the date. And that time portion indicates the time at which the [function or triggering] statement began to execute. So that means the start of the day in a DATETIME data type looks like: 2010-06-24 00:00:00
(YYYY-MM-DD HH:MM:SS, to microsecond precision), which NOW() would show something like 2010-06-24 14:24:31
...
Here are your options:
SELECT * FROM events WHERE event_date >= DATE(NOW())
SELECT * FROM events WHERE event_date >= DATE(CURRENT_TIMESTAMP)
SELECT * FROM events WHERE event_date >= CURRENT_DATE()
SELECT * FROM events WHERE event_date >= CURRDATE()
Your issue is that now() is very accurate. So dates for today and before now because they started at the beginning of the day.
Use this:
select * from events where datediff(event_date, now()) >= 0;
You could also do
<?php
$db->query("SELECT * FROM events WHERE UNIX_TIMESTAMP(event_date) >= UNIX_TIMESTAMP(NOW())");
?>
Which is more accurate than using CURTIME() if by any chance your using time as well as date