Allow users to rate a comment once PHP MySQL

你离开我真会死。 提交于 2019-12-11 05:30:08

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/8617624/allow-users-to-rate-a-comment-once-php-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!