Help with datetime php
I am trying to integrate voting system in a website where a registered user can vote only once a day. So suppose if he votes today at 10 pm then again tomorrow at 10 am he can vote but he cannot vote again the very开发者_运维问答 same day. How do I implement this using php, mysql. I don't have any specific code as such.
Use a unique key on the table you use to store votes, something like:
CREATE TABLE vote (
`Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`UserId` int(10) unsigned NOT NULL,
`Selection` tinyint(3) unsigned NOT NULL,
`VotedDate` date NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY (`UserId`,`VotedDate`)
);
You can check this prevent duplicate votes simply:
mysql> insert into vote (UserId, Selection, VotedDate) values (1, 2, now());
Query OK, 1 row affected, 1 warning (0.01 sec)
mysql> insert into vote (UserId, Selection, VotedDate) values (1, 2, now());
ERROR 1062 (23000): Duplicate entry '1-2011-06-11' for key 'UserId'
Here's the general idea, since that seems to be what you're after:
- When a registered user votes, store the vote as a row in your database with the id of the user, the id of the item being voted on, and the current time.
- The next time a user votes - to let them vote again on the same item, check the time of their last vote (lookup by user id and item id) and see if it was more than 24 hours ago. If not, do not accept the vote.
In this case, time zone won't matter because you are always using the system time.
Well you could do this:
/* Assuming $timestamp to be the timestamp of the latest vote of the user */
$datenow = date("m.d.y");
$datetimestamp = date("m.d.y", $timestamp);
if ($datenow != $datetimestamp) { /* user can vote */ }
精彩评论