I have a mysql tables...
'users' with uname(a string) as the primary key. 'posts' with id as the primary key.
'posts' has a columnm- 'votes'
When a user is logged in, he can vote posts. The problem is how do i stop him from voting more than once?
Link:(Note: $q is id of the post)
<a href='./vote.php?upid=".$q."'>Upvote</a>
PHP:
if(isset($_GET["upid"])) {
$plus = $_GET["upid"];
$query = "UPDATE posts SET votes = votes + 1 WHERE id='$plus'";
$result = mysqli_query($dbc, $query) or die('Error querying database!');
}
Take two steps:
Onclick set the link's style to display:none
. or hide()
with jQuery. (UX friendly) (PHP: on future page loads, do not present the link if a vote is already cast by the user.)
In your database, save the action in a new/separate table that only allows INSERT only if unique combination of userid and postid. Then you can leverage that table to count the total votes for the post id.
p.s. By storing individual votes using unique post id and user id, you can also allow a user to undo their vote if you wish.
Are you keeping a record of who was up voted what? If so, you could do an if statement around the up vote link and only actually display the link if they hadn't voted?
This is the best way, that I can think of to do it as, although you could store cookies / session data, they could obviously easily be bypassed. EDIT: Just to be clear, I am saying that you should not be using session / cookie data for security reasons, however as mickmackusa mentioned in a comment, using sessions would become awfully bloated as more and more posts got voted on.