1

I have a voting system which allows for users to upvote and downvote on items. I am looking to improve the system because users can vote multiple times. Below you can see my code.

<h4> Votes </h4>

<table>
<tr>
<th>Up-Votes</th>
<th>Down-Votes</th>
<tr/>
<tr>
<?php 
 mysql_connect("localhost", "root", "PASS") or die(mysql_error()); 
 mysql_select_db("DBNAME") or die(mysql_error()); 

 if ( isset( $_POST['Upvote'] ) )
 {

 mysql_query ("UPDATE reports SET up = up + 1 WHERE reportID = $id"); 

 } else if (isset( $_POST['Downvote'] ))
{
 mysql_query ("UPDATE reports SET down = down + 1 WHERE reportID = $id"); 
}

$data = mysql_query("SELECT * FROM reports WHERE reportID = $id") or die(mysql_error()); 

while($ratings = mysql_fetch_array( $data )) 
{ 

Echo "<td>" .$ratings['up']."</td>"; 
Echo "<td>" .$ratings['down']."</td>"; 

} 

?>
</tr>
</table>
<br/>
<form method='POST'>
<input type='submit' value='up' name='Upvote' class="myButton">
<input type='submit' value='down' name='Downvote' class="myButton">
</form> 

Does anybody have any suggestions which could prevent duplicate votes?

There are potentially thousands of items on my system, I am unsure as to how I can make a user be exempt from voting on particular reports

Cheers

user2320010
  • 93
  • 1
  • 8

2 Answers2

1

Make a database of votes:

CREATE TABLE Votes (
    Value int,
    User int
);

Value is 1 for upvotes, -1 for downvotes, User is the user ID. Just override an existing column when a vote is already placed:

if (mysqli_fetch_array(mysqli_query($con, "SELECT FROM `Votes` WHERE `User` = ".$theuserid)) {
    mysqli_query("UPDATE `Votes` SET `Value` = ".$mynewvalue." WHERE `User` = ".$theuserid);
} else {
    mysqli_query("INSERT INTO `Votes`(`User`,`Value`) VALUES (".$theuserid.",".$mynewvalue.")");
}

To get the sum of the votes, use:

SELECT sum(Value) FROM Votes
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
bjb568
  • 11,089
  • 11
  • 50
  • 71
0

And then right this in your php

$voted = $this->getUserVoted(escape($_POST['user']));
    if($voted) { $this->addError($language_votes['you_already_rated']); return; }