MySQL: Find All Records Submitted in the last Hour

analog-clockIn the middle of writing a quick support page email notification system for Touchwork, I realised that I needed to add a check which would limit a user from submitting a query or bug report to a certain amount of entries per hour.

The easiest solution as it turned out was to run the check using a clever little SQL string, which looked like this:

SELECT * FROM `touchwork-support` WHERE DATE_SUB(NOW(),INTERVAL 1 HOUR) <= `ts-timestamp`

ts-timestamp is nothing more than a datetime column in the table, populated with the time of submission on every record submit. The SQL itself calculates the date time left over when subtracting an hour from the current date time, which is obviously then compared against the timestamp column to grab query-satisfying records.

With the result in hand, you simply check the num_rows value of the record set and if it is larger than the cut-off you imposed, return a suitable error message.

Couldn’t be easier! :)

For a more complete example:

$sql = “SELECT * FROM `touchwork-support` WHERE DATE_SUB(NOW(),INTERVAL 1 HOUR) <= `ts-timestamp`”;
$result = mysql_query($sql);
if (mysql_num_rows($result) >= 4)
{
echo ‘Oopsie!’;
}

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials and tagged datetime, hourly restriction, , . Bookmark the permalink.
    blog comments powered by Disqus