0

Here's a bit of my code:

if(isset($_GET['nyaste'])) {
$query = mysql_query("SELECT * FROM jokes ORDER BY id DESC LIMIT 0, 12") or die(mysql_error());
while ( $result = mysql_fetch_assoc($query) ) { 
$id = $result["id"];  
if(isset($_POST['voteup'])) {
mysql_query("UPDATE jokes SET ranking = ranking + 1 WHERE id = $id ") or die(mysql_error());  
}  
if(isset($_POST['votedown'])) {
mysql_query("UPDATE jokes SET ranking = ranking - 1 WHERE id = $id ") or die(mysql_error());  
}

now, my problem is that when i upvote/downvote something, it adds/removes 1 rating on all the posts instead of just the one you meant to rate. How do you make the votes unique or something

finst33
  • 141
  • 1
  • 3
  • 11
  • 1
    Please stick to one question per post. Choose the one you'd rather have answered first and remove the other one. – Mark Byers Jun 23 '12 at 20:20
  • 1. Create a variable that holds the votes and then add 1 e.g. $rankig++; then call mysql_query(); 2. To make the voter to vote once you need to store his ip in a file or a table and then check if that ip is in the file or not – Ionel Lupu Jun 23 '12 at 20:23
  • First you select all the posts, then loop through all of them and up/downvote each in turn. Why, if you want to rate only one? Where do you have the id of the post you actually want to rate? – JJJ Jun 23 '12 at 20:23

2 Answers2

0

This line

$query = mysql_query("SELECT * FROM jokes ORDER BY id DESC LIMIT 0, 12")  ...

fetches some jokes from the table. Then the script changes all of them passing through

while ( $result = mysql_fetch_assoc($query) )

That means if you have either 'voteup' or 'votedown' in your _POST the loop will modify all fetched jokes.

To fix this you have to know id of the joke voted. You can use some request variable to indicate it.

Maksym Polshcha
  • 18,030
  • 8
  • 52
  • 77
0

Do not include the _POST checks inside the while() statement for your query.

For example:

if(isset($_GET['nyaste'])) {

$add_to_vote = 0;

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

$add_to_vote++;

}

else if(isset($_POST['votedown'])) {

$add_to_vote--;

}

$query = mysql_query("SELECT * FROM jokes ORDER BY id DESC LIMIT 0, 12") or die(mysql_error());
while ( $result = mysql_fetch_assoc($query) ) { 

$id = $result["id"];  

if($add_to_vote != 0){

// update the current ID
$query = mysql_query("UPDATE jokes SET ranking = ranking + $add_to_vote WHERE id = '$id'") or die(mysql_error());

}

}

But you should only be updating one ranking at a time. Your script is grabbing 0-12 jokes and updating them based on one _POST variable (voteup or votedown).

bgallz
  • 111
  • 6