I am getting a count of scans in a database. The time field is a mysql timestamp (2011-10-20 14:15:12). I have a function that lets me set a timeframe like 30 days, 60 days etc… this was working for weeks. Then I just noticed it broke.
function getScans($timeframe = 0)
{
if ($timeframe != 0) {
$query = 'SELECT COUNT( * )
FROM stats
WHERE time <= curdate( )+1
AND time >= curdate( )-' . ($timeframe - 1);
} else {
$query = 'SELECT COUNT( * )
FROM stats';
}
$result = mysql_query($query);
$row = mysql_fetch_array($result);
return $row[0];
}
I know you have all heard this before but this was completely working last week. I went back today and noticed that when the $timeframe is other than 0, it no longer works. Any help is appreciated.
The problem is this:
curdate( )+1yields20111131(to day 2011-11-30) not what I believe you expect,2011-12-01, the same is true for the latercurdate()call. It’s probably been working fine because earlier in the month the calls have resulted in correct dates and MySQL accepts the formatting, but now it fails to alert on “impossible” dates. Closing in on next month, things start acting up.The query should be rewritten like:
You could do something like this:
But it isn’t the safest approach if
$timeframecould be supplied by a user or the like. Rather, you should consider using something like:or, better yet, search SO for tips on sanitizing user input before adding it to an SQL statement.