I save users sing-in information using the fields below:
user_id, login_date, login_time, status
After each attempting for sign-in, a record will insert into database using true or false status. I want to lock user if he/she has 3 failed logins in the last 3 minutes. So I need to use the current time and calculate its difference with 3 last records of table in minute format.
My questions are:
1- Which one is better to do this time calculation? PHP or MySQL?
2- Depends on your suggestion, which function is better for it?
Thank you.
Following query returns all User_Id's according your conditions:
select user_id from t
where login_date= CURDATE()
and login_time>TIMESTAMPADD(MINUTE,-3,CURTIME())
and status = 'f'
group by user_id
having count(*)>3
Different usage. If I were you, I will record the last failed login date & time in database, such that you can fetch the last failed login time from database along with the user data from database.
Do the comparison in PHP or MySQL is okay.
However, you should bear in mind that MySQL server & Web server should have same timezone and time should be synchronized, or your result will not be accurate.
Considering you need to do a lot of other things aswell, I say use php. You could retrieve the last 3 records for a user when he tries to log in using
SELECT login_date, login_time, status FROM table WHERE user_id=$id ORDER BY login_DATE DESC LIMIT 3
Then in PHP you can do the check. If it fails you still need to inform the user he is locked, lock the user (other table?) and return false for login.
in php you could do some checking like
If you use timestamps you could simple do time_x - time_y to get the difference in seconds, your total calculation will be: (time_x - time_y) / 60 and your query will look something like this:
SELECT user_id, login_date, login_time, status, ((login_time-NOW()) / 60) as differenceColomn FROM usertable