Skip to content
Advertisement

PHP – I want the user to have no possibility to upvote more than one time

I am working on a small social network with PHP and MySQL I want the users to have the possibility to upvote a post, and I already did this but the problem is that I want the user to be able to upvote only one time.

Here is my PHP code:

if (isset($_POST['heart']))
{ 
  $identificateur = $_POST['hide'];
  $Q = "UPDATE posts  SET avis = avis + 1 where id=$identificateur ";
  $bdd->query($Q);
}

This is the form of the upvote button :

<form action="p.php" method="POST">
        <label><?php 
        if ($avis != 0)
                    {
                        echo $avis; 
                    }
        ?></label>
        <input type="hidden" value="<?php echo "$id" ?>" name="hide">
        <input type="submit" value=" " id="heart" name="heart"> 
</form>

Every user should have the right to click on the up vote icon only once. Thank you very much in advance.

Advertisement

Answer

You need to have a second table, that has two fields, post_id and voter_id. (post_voter).post_id has a foreign key containing the id of the post table and voter_id has foreign key to the user table. This table specifies voters of a post and posts that users have voted for. When a user tries to upvote a post, you must check post_voter table and get count of rows which have the post_id equal to the post’s id and voter_id equal to the user’s id. If count = 0, this means the user has not upvoted the post, yet, and he can vote for it now. Otherwise, the user upvoted the post already and he can’t upvote it again.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement