我有一段代码(用于)通过表格条目进行计数,以找出对特定问题的投票数。
这是表格:
USER | answer_id | poll_id |
------------------------------------
usename 5 1
user2 4 1
user3 5 1
等等。基本上每次用户投票时,都会创建一个单独的行,并且该answer_id
列包含他们投票的问题编号。
在我将代码从 sql 更新为 PDO 语句后,查找票数的代码停止工作,只找到最近的投票,因此只返回一票。这是我更新的代码:
// Get Votes
$q = 'SELECT * FROM votes WHERE poll_id = :poll_id';
$params = array(':poll_id' => 1);
$stmt = $pdo->prepare($q);
$stmt->execute($params);
while ($row = $stmt->fetch()) {
$votes = array(); //the array that will be containing all votes ( we add them as we retrieve them in a while loop )
$total_votes = 0;
$answer_id = $row['answer_id'];
$votes[$answer_id] = (int)$votes[$answer_id]+1; //add 1 vote for this particulair answer
$total_votes++;
}
// End Get votes
这是它开始处理这些结果的地方
// Start Get answers
$q = 'SELECT * FROM answers WHERE poll_id = :poll_id';
$params = array(':poll_id' => 1);
$stmt = $pdo->prepare($q);
$stmt->execute($params);
while ($row = $stmt->fetch()) { //loop through all answers this poll has
$id = $row['id']; //the id of the answer -> the amount of votes for each answer we stored in $votes[id_of_answer] so for this id it would be $votes[$id]
$width = round((int)$votes[$id]/$total_votes*99+1); //100% of votes
echo ''.$row['answer'].'
('.(int)$votes[$id].' vote'.((int)$votes[$id] != 1 ? "s":"").')
';
}
这是 MySQL 中的原始代码:
$get_votes = mysql_query("SELECT * FROM votes WHERE poll_id = '$id' "); //select all votes to this poll
$votes = array(); //the array that will be containing all votes ( we add them as we retrieve them in a while loop )
$total_votes = 0;
while($vote = mysql_fetch_assoc($get_votes)) { //retrieve them
$answer_id = $vote['answer_id'];
$votes[$answer_id] = (int)$votes[$answer_id]+1; //add 1 vote for this particular answer
$total_votes++;
}
//now loop through the answers and get their corresponding amount of votes from $votes[id_of_answer]
$get_answers = mysql_query("SELECT * FROM answers WHERE poll_id = '$id' ");
while($answer = mysql_fetch_assoc($get_answers)) { //loop through all answers this poll has
$id = $answer['id']; //the id of the answer -> the amount of votes for each answer we stored in $votes[id_of_answer] so for this id it would be $votes[$id]
$width = round((int)$votes[$id]/$total_votes*99+1); // 100% of votes
echo ''.$answer['answer'].'
('.(int)$votes[$id].' vote'.((int)$votes[$id] != 1 ? "s":"").')
';
}
谁能告诉我哪里出错了?它是//Get Votes
我努力弄清楚我所做的事情的一部分。据我所知,没有什么不公平的。