Question

I have a website where users can rate comments that are left on pages. Each comment has a unique ID (E.g. 402934) If I want users to be able to thumb-up/thumb-down said comments I can see how I would make a simple counter code to keep track of the number of thumb-ups vs thumb-downs but how can I make sure that each user only ranks said comment once. I was going to make a database with each comment number as a row and in that row having an array of all the users that have ranked it thumbs up and all the users that have ranked it thumbs down but I had a feeling that wasn't the best way. My next thought was to have a table for each user and then having an array showing all the comments said user has ranked. It would probably run faster this way (e.g. checking from a user's 150 rankings verse a comment's 6050 rankings but I still feel like there is a better way... any ideas?

Was it helpful?

Solution

Create a new table with user_id, comment_id and vote TINYINT(1).

A value of 1 in vote is a thumbs up, A value of 0 in vote is a thumbs down.

Have a UNIQUE KEY constraint on (comment_id, user_id).


If you follow the above it will be easy to check whether a user has cast a vote on a specific comment, if you'd like to be able to quickly (as in fast execution) see all the comments a user has made you should also add an INDEX to user_id.


When a user votes you could use REPLACE INTO to user_comment_thumbs, such as the below:

REPLACE INTO `user_comment_thumbs` (user_id,comment_id,vote)
VALUES (@user_id, @comment_id, @vote);

If the user has already made a vote the entry in the table will be updated, otherwise a new row will be inserted.

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