behz4d
behz4d

Reputation: 1849

check if it happens in 24 hours

Imagine we're giving users the ability to send emails using our website, but we want to limit them to not send more than 30 emails per day(24 hours).

So, by sending each email we're gonna insert a record into our table, then while he/she wants to send another one, we check if he has sent more than 30 emails during 24 hours or not.

How we could check this with PHP?

we query db, we got 20 records for this user, the date of records are:

2012-08-14 13:10:58
2012-08-14 12:45:47
2012-08-14 16:32:18
2012-08-14 19:10:40
...
...
...

How we could achieve such rule?

Thanks

Upvotes: 3

Views: 674

Answers (1)

Fluffeh
Fluffeh

Reputation: 33502

Don't check it in PHP, use a simple query like this to get the answer out of he database right off the bat.

select 
    count(*) 
from 
    yourTableName 
where 
    dateCol>date_sub(now(), interval 1 day) 
    and userID=...

This will give you the count.

Edit: As Boris points out, this will count per day, you could change it to check for the last 24 hour period like this:

select 
    count(*) 
from 
    yourTableName 
where 
    dateCol>date_sub(now(), interval 24 hour) 
    and userID=...

Edit 2: After checking this, Riad correcly points out, these two do in fact return the same value. The 1 day is treated as exactly 1 day, not a calendar date. If the date column has a datetime of '2012-08-13: 13:00:00' a date_sub( dateCol, interval 1 day) will return '2012-08-12: 13:00:00'.

Upvotes: 5

Related Questions