我正在做一个学校项目,我需要允许用户对图片进行投票。用户可以上下一张图片。这是他们可以随时更改投票的想法,但他们无法撤消投票,因此一旦他们投票,它要么向上要么向下。
我一直在尝试一些事情,但我似乎无法让它发挥作用。它在用户第一次按下赞成票时起作用,然后用户可以将他的投票更改为反对票。但是当他再次尝试投票时,什么都没有发生,这一直困扰着我一段时间,我将不胜感激任何帮助。
到目前为止,这是我的代码:
if (isset($_SESSION['loggedin'])) {
$result = mysql_query("SELECT * FROM user2pics WHERE picid = $id AND userid = $user");
if (mysql_num_rows($result) == 0) {
$votes_up = $cur_votes[0] + 1;
$resultaat = mysql_query("UPDATE pics SET likes = $votes_up WHERE picid = $id");
if ($resultaat) {
$query = mysql_query("INSERT INTO user2pics (picid, userid, vote) VALUES ($id, $user, 1)");
if ($query) {
$effectiveVote = getEffectiveVotes($id);
echo $effectiveVote . " votes";
} elseif (!$query) {
echo "Failed!";
}
} elseif (!$resultaat) {
echo "Failed insert in pics!";
}
} else {
$row = mysql_fetch_array($result);
if ($row['vote'] == 0) {
$votes_down = $cur_votes[0] + 1;
$result = mysql_query("UPDATE pics SET likes = $votes_up WHERE picid = $id");
if ($result) {
$resultaat = $mysqli -> prepare("UPDATE user2pics SET vote = 1 WHERE picid = $id AND userid = $user");
$resultaat -> execute();
$effectiveVote = getEffectiveVotes($id);
if ($resultaat -> affected_rows == 1) {
echo $effectiveVote . " votes";
}
}
} else {
$effectiveVote = getEffectiveVotes($id);
echo $effectiveVote . " votes";
}
}
} else {
echo "Please login first!";
}
} elseif ($action == 'vote_down'){
if (isset($_SESSION['loggedin'])) {
$result = mysql_query("SELECT * FROM user2pics WHERE picid = $id AND userid = $user");
if (mysql_num_rows($result) == 0) {
$votes_down = $cur_votes[1] + 1;
$resultaat = mysql_query("UPDATE pics SET dislikes = $votes_down WHERE picid = $id");
if ($resultaat) {
$query = mysql_query("INSERT INTO user2pics (picid, userid, vote) VALUES ($id, $user, 0)");
if ($query) {
$effectiveVote = getEffectiveVotes($id);
echo $effectiveVote . " votes";
} elseif (!$query) {
echo "Failed to dislike!";
}
} elseif (!$resultaat) {
echo "Failed insert in pics!";
}
} else {
$row = mysql_fetch_array($result);
if ($row['vote'] == 1) {
$votes_down = $cur_votes[1] + 1;
$result = mysql_query("UPDATE pics SET dislikes = $votes_down WHERE picid = $id");
if ($result) {
$resultaat = $mysqli -> prepare("UPDATE user2pics SET vote = 0 WHERE picid = $id AND userid = $user");
$resultaat -> execute();
$effectiveVote = getEffectiveVotes($id);
if ($resultaat -> affected_rows == 1) {
echo $effectiveVote . " votes";
}
}
} else {
$effectiveVote = getEffectiveVotes($id);
echo $effectiveVote . " votes";
}
}
} else {
echo "Please login first!";
}
}
$cur_votes 定义为:
$cur_votes = getAllVotes($id);
function getAllVotes($id) {
$votes = array();
$q = "SELECT * FROM pics WHERE picid = $id";
$r = mysql_query($q);
if (mysql_num_rows($r) == 1)//id found in the table
{
$row = mysql_fetch_assoc($r);
$votes[0] = $row['likes'];
$votes[1] = $row['dislikes'];
}
return $votes;
}
function getEffectiveVotes($id) {
/**
Returns an integer
**/
$votes = getAllVotes($id);
$effectiveVote = $votes[0] - $votes[1];
return $effectiveVote;
}