Question

I'm building a website which has a feature which ressembles SE's voting system. I'm trying to restrict users from voting more than once per post.

Currently, I was thinking of having a field in my user mysql database that would keep a list of ids (corresponding to posts) that the user has already voted on. Each time the user casts a vote, the array is checked against the current post's id. If it is found an error message is displayed, if not the vote goes through and the id is now part of the user's "already voted on" list.

This seems like an odd way of doing this. Is it an efficient method? What method would be better/best?

Was it helpful?

Solution

I would create a separate table called user_post that would have the user_id and post_id - in fact, you can make those columns a multi-column primary key.

When a user votes on a post, you can use the following query:

REPLACE INTO user_post (user_id, post_id, vote) VALUES (:userId, :postId, :vote)

Replace is essentially saying 'insert unless there is a unique key conflict, if so, update the row'. Or, you can use:

INSERT IGNORE INTO user_post (user_id, post_id, vote) VALUES (:userId, :postId, :vote)

which essentially says 'insert unless there is a unique key conflict, if so, ignore' (if you only want to keep the first vote).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top