I'm trying to add vote up / vote down functions for each item I have in a table. I am currently working on implementing this one here: www.technabled.com/2009/02/reddit-style-voting-with-php-mysql-and.html
But, it doesn't work for me. Once action is run, it always returns "FAILED!", and I can't figure out what I'm doing wrong anymore.
This is what's inside my votes.php
page.
function getAllVotes($id)
{
$votes = array();
$q = "SELECT * FROM cover WHERE id='$id' ";
$r = mysql_query($q) or die("Error: ". mysql_error(). " with query ". $q);
if(mysql_num_rows($r)==1) {
$row = mysql_fetch_assoc($r);
$votes[0] = $row['votes_up'];
$votes[1] = $row['votes_down'];
}
return $votes;
}
function getEffectiveVotes($id)
{
/**
Returns an integer
**/
$votes = getAllVotes($id);
$effectiveVote = $votes[0] - $votes[1];
return $effectiveVote;
}
$id = $_POST['id'];
$action = $_POST['action'];
//get the current votes
$cur_votes = getAllVotes($id);
//ok, now update the votes
if($action=='vote_up') //voting up
{
$votes_up = $cur_votes[0]+1;
$q = "UPDATE cover SET votes_up = $votes_up WHERE id = $id";
}
elseif($action=='vote_down') //voting down
{
$votes_down = $cur_votes[1]+1;
$q = "UPDATE cover SET votes_down = $votes_down WHERE id = $id";
}
$r = mysql_query($q);
if($r) //voting done
{
$effectiveVote = getEffectiveVotes($id);
echo $effectiveVote." votes";
}
elseif(!$r) //voting failed
{
echo "Failed!";
}
And if it matters, here's the table structure for the columns used:
votes_up and votes_down:
Type: int(11)
/ Null: No
/ Default: 0
column id:
Type: int(8)
/ Null: No
/ Extra: AUTO_INCREMENT
And I do my checking using parameters:
site.com/votes.php?action=vote_up&id=123
Hopefully someone could spot the error. Thank you for your time and assistance!