4

I am building a webservice using php & mysql, and would like to limit requests from each apikey to (x) amount within (y) time.

To achieve this, i count the records added to the the log from each apikey within a period using a sql statement like this:

SELECT COUNT(*) FROM ws_account_log WHERE account_log_account_id='1' AND account_log_timestamp > DATE_SUB(now(), INTERVAL 1 HOUR)

This gives me the a rolling hourly count, which is fine, but I would like a hard limit on the monthly count. eg how many rows have been added since 00:00 of the first day of the current month.

I have seen examples using stored procedures and different syntax, I would like an answer that will work on MYSQL please. Also, if possible the fastest implementation as one of the services provides autocomplete functions, therefore the log table is rather large.

Thanks

Graham
  • 318
  • 1
  • 16

2 Answers2

5
SELECT COUNT(*)
FROM ws_account_log
WHERE
      account_log_account_id='1'
  AND account_log_timestamp >= SUBDATE(CURDATE(), DAYOFMONTH(CURDATE())-1)
eggyal
  • 122,705
  • 18
  • 212
  • 237
0

Calculate timestamp to the moment you want using php, then pass it to mysql query.

$date = mktime(0, 0, 0, date("n"), 1, date("Y"));
$mysqldate = date( 'Y-m-d H:i:s', $date );
$query = " ... AND account_log_timestamp > ".$mysqldate;
Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127