0

I have a php script that looks like this (shortened/edited for clarity of course):

$result = mysqli_query($link, 'SELECT date FROM table');
while ($row = mysqli_fetch_assoc($result)) {
if ($row["date"] < time())
{
do some stuff
}
else
do something else

The date is stored in a DATE field in MySQL. I have no interest in storing time and only the date is stored in that field in XXXX-XX-XX format.

How can I check if the retrieved date is today or earlier? By using time() there, which was the last thing I ended up trying, my script is acting as if all retrieved dates are today or earlier, even when they are not.

Thank you for any help with this.

John E
  • 33
  • 4

2 Answers2

2

You should perform the comparison in the SQL query.

Have a look at: mysql date comparison with date_format

Community
  • 1
  • 1
Matthew
  • 36
  • 1
  • Thank you, looking at that post now. But is that suitable if I need that query to retrieve ALL dates, as it does other formatting with other dates that don't apply to the 'if' section (some dates are in the future, for upcoming things). I should have been more clear on that in my original post. I'll edit to reflect that. – John E Oct 06 '13 at 11:42
  • I figured it out, just added a separate query: SELECT curdate(). Then created a $today variable and compared my results to that. if $date < $today { blah }". Works beautifully, thank you! – John E Oct 07 '13 at 00:44
  • @JohnE: you can do this in one query, like I suggested in my answer. Then just use `if ($row['isTodayOrEarlier']) {` – Glavić Oct 10 '13 at 13:13
0

You can check if date is today (or earlier) in the SQL statement:

SELECT `date`, `date` <= CURDATE() AS isTodayOrEarlier
FROM table

or

SELECT `date`, IF(`date` <= CURDATE(), 1, 0) AS isTodayOrEarlier
FROM table
Glavić
  • 42,781
  • 13
  • 77
  • 107