我很抱歉我的英语不好。我希望你能理解 :) 所以首先最好使用mysqli或 pdo。如果您创建新的投票表,将来您将有更多选择(加入用户行列,平均具体用户排名,验证用户之前是否投票过,...)
做的灵感:用户端(用于发送使用jquery - ajax):
<a href="IDOFPROBLEM" title="VoteUp" class="voteUp">VoteUp</a>
<script>
$(document).ready(function() {
$(".voteUp").click(function(e) {
e.preventDefault();
var id = $(this).attr("href");
$.ajax({
type: "POST",
//This is destination of php script
url: "YOURVOTEUPFILE.php?vote=up",
data: {id: id}
})
.done(function(msg) {
//msg contains data from php script so you can show message to user good or bad :)
alert(msg);
});
});
});
</script>
服务器端:
final class manageVote {
/**
* Id of problem
* @var int|string
*/
private $voteFor;
/**
* Id of user
* @var int|string
*/
private $whoVote;
/**
* Mysqli
* @var \mysqli
*/
private $database;
/**
* Construct - initialize variable
* @param int|string $voteFor
* @param int|string $whoVote
* @param \mysqli $db
*/
public function __construct($voteFor, $whoVote, &$db) {
$this->voteFor = $voteFor;
$this->whoVote = $whoVote;
$this->database = $db;
}
/**
* Try to make vote
* @param string $upOrDown "up" or "down"
* @return boolean
*/
public function vote($upOrDown) {
if (!$this->verifyIfUserCannote() || ($upOrDown != "up" && $upOrDown != "down"))
return false;
//Change database name to your name
//Better solution is sql table for all ranks
//And you need "whoVote" because I think one problem - one vote for one user
/*
* Table could be:
* idvote PK NN AI
* vote INT NN
* idproblems FK NN
* whoVote FK NN
*/
$sql = "INSERT INTO `DATABASENAME`.`problems` (`idproblems`, `vote`, `whoVote`) VALUES('" . $this->voteFor . "', '" .
($upOrDown == "up" ? 1 : -1) . "', '" . $this->whoVote . "')";
$query = $this->database->query($sql);
if (!$query)
return false;
return true;
}
private function verifyIfUserCannote() {
$sql = "SELECT COUNT(*) AS 'cnt' FROM `DATABASENAME`.`problems` WHERE `idproblems` = '" . $this->voteFor . "' AND `whoVote` = '" . $this->whoVote . "'";
$query = $this->database->query($sql);
if (!$query)
return false;
$result = mysqli_fetch_array($query);
return ($result["cnt"] == 0 ? true : false);
}
}
if (isset($_GET["vote"])) {
$voteClass = new manageVote($_POST["id"], $someYourIdentificatorWhoVote, $mysqliDatabaseReference);
echo ($voteClass->vote($_GET["vote"]) == true ? "TRUE" : "FALSE");
}
else
echo "FALSE";
对于投票的最终排名,请使用 SQL 命令 SELECT SUM(vote) FROM ....... GROUP BY idProblems