tags:

views:

51

answers:

2

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....

A: 
$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. :)

Thomas Clayson
Make sure you have a index across the three columns to improve this lookup.
bramp
No, *use* COUNT - you're sending back all the column data in the table, only to completely ignore it for sake of what amounts to COUNT.
OMG Ponies
You don't have to select all of it - send back just the ID if you want. Even if you count you have to send back something.
Thomas Clayson
A: 

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')";

SimpleCoder
I would assume (read "hope") that username was escaped before the user was signed up... and the string that is being used is just this recycled field, rather than a user input.
Thomas Clayson
Using Oauth so Username comes from the Oauth session, its not input by the user via the site.
danit