tags:

views:

75

answers:

2

I want to create a function that allows me to ban an account for 10days. In the dbc, I have a field called "ban" and Boolean of 1=notban, 0=ban. I also have a field called "date_banned" which is just the timestamp of when the user got banned.

My question is how do I create a time frame of 10days from the date the user was banned?

ex: James was banned on "2010-05-03 20:43:48". So how can I go about adding 10days to the timestamp? And after 10days, it would set the "ban" equal to 1(which is not banned).

EDIT: how can i show how many days the user has left of a ban? ex: 8 more days till unban

Can I...do NOW()-$date_banned? or how do I subtract the ban date from the current date?

+4  A: 

unban_date=DATE_ADD(NOW(), INTERVAL 10 DAY) should do the trick

Then just have a cron that checks to see if anybody's unban_date is in the past, and you can update your banned flag.

webdestroya
So I need another field for unban_date (which would just be 10days later) but how do I check the current date with the unban_date?
ggfan
`UPDATE bans SET ban=1 WHERE unban_date<=NOW()`
webdestroya
Ahhh that was easy enough. thanks :)
ggfan
Actually, there'd be no need for the cron job. The "has ban expired" check could be done within the login function when the banned user tries to get in. If it's not passed, you deny login with an appropriate message, otherwise just reset the ban flag and let them in.
Marc B
+5  A: 

To add 10 days to your date_banned field in MySQL, you can simply use the DATE_ADD() function. You could do the following check when the user tries to log-in, to see if the ban has expired:

... WHERE NOW() > DATE_ADD(date_banned, INTERVAL 10 DAY);

Then you may want to toggle the ban field when the user tries to log in. Otherwise you can run a scheduled job every day, or at any other rate, that checks for expired bans and updates this field accordingly.

However you do not actually need the ban field to check if a user is banned or not. In fact you may want to consider eliminating it. Actually, I would go further and suggest to use a banned_until instead of date_banned (or use them both). The banned_until field would make your queries simpler, and would allow you to predefine arbitrary ban durations at the time the ban is issued. In this case, when a user logs in, you can simply do the following check:

... WHERE NOW() > banned_until;

UPDATE:

To get the number of days remaining until the end of the ban, you can use the TIMESPANDIFF() function in MySQL:

SELECT TIMESTAMPDIFF(DAY, NOW(), DATE_ADD(date_banned, INTERVAL 10 DAY)) ...

Or if you were to use the banned_until field, it will be even shorter:

SELECT TIMESTAMPDIFF(DAY, NOW(), banned_until) ...
Daniel Vassallo
That's a good idea! I'll just have banned_until and set the timelimit to my preference.
ggfan