1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?php
include("database.php");

$id = mysql_real_escape_string($_POST['id']);
$action = mysql_real_escape_string($_POST['action']);

function getAllVotes($id)
	{
	/**
	Returns an array whose first element is votes_up and the second one is votes_down
	**/
	$votes = array();
	$q = "SELECT * FROM comments WHERE id = '$id'";
	$r = mysql_query($q);
	if(mysql_num_rows($r)==1)//id found in the table
		{
		$row = mysql_fetch_assoc($r);
		$votes[0] = $row['voteup'];
		$votes[1] = $row['votedown'];
		}
	return $votes;
	}

function getEffectiveVotes($id)
	{
	/**
	Returns an integer
	**/
	$votes = getAllVotes($id);
	$effectiveVote = $votes[0] - $votes[1];
	return $effectiveVote;
	}


//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 comments SET voteup = $votes_up WHERE id = $id";
}
elseif($action=='vote_down') //voting down
{
	$votes_down = $cur_votes[1]+1;
	$q = "UPDATE comments SET votedown = $votes_down WHERE id = $id";
}

$r = mysql_query($q);
if($r) //voting done
	{
	$effectiveVote = getEffectiveVotes($id);
	if($effectiveVote > 0) { echo "<font color='#00CC33'><b>+".$effectiveVote."</b></font>"; }
	else if($effectiveVote < 0) { echo "<font color='#990000'><b>".$effectiveVote."</b></font>"; }
	else { echo "<font color='#000000'><b>".$effectiveVote."</b></font>"; }
	}
elseif(!$r) //voting failed
	{
	echo "Failed!";
	}
?>