CLiown
CLiown

Reputation: 13843

Checking if some one has already voted

Im using a simple ajax script to allow users to vote against multiple posts on a page. However I dont want the same user to vote against the same post more than once, to try and avoid this I log the users, ID, Username and the ID of the post to which they have voted in a database.

Like so:

$updatevoters = "INSERT INTO voters VALUES('$userid', '$id', '$username')";

What I now need to do is before submitting the vote to the database is make sure that the user hasnt already done so.

How can I query the database, Im thinking of using COUNT or something similar, to check if there are any matches?

Im not sure how to take all 3 variables $userid, $id and $username and compare against the voters table.

Essentially I'd like to be able to build an IF:

If ($count = 0) {
  ADD THE VOTE TO TABLE
} else {
  //DIE
}

Any help appreciate....

Upvotes: 3

Views: 1086

Answers (2)

Chris Laplante
Chris Laplante

Reputation: 29658

Fetch the voting records for the specific user ID. If the count is zero, allow them to vote.

And please tell me that $username is escaped or sanitized somewhere before the line "INSERT INTO voters VALUES('$userid', '$id', '$username')";

Upvotes: 0

Thomas Clayson
Thomas Clayson

Reputation: 29925

$sql = "SELECT * FROM voters WHERE userid='$userid' AND id='$id' AND username='$username'";
$result = mysql_query($sql);
if(mysql_num_rows($result)){
    // there ARE rows so user has already voted
}
else{
    // no rows... user hasn't voted yet
}

no need for count... if they're in the database then they've voted. :)

Upvotes: 2

Related Questions