0

我有一个 PHP 脚本,它允许基于登录系统进行投票。

我正在尝试将所有代码切换到 PDO 而不是 MySQL。我无法切换这段特定的代码。这是原文:


$get_votes = mysql_query("SELECT * FROM votes WHERE poll_id = 1 "); //select all votes to this poll

$votes = array(); //the array that will be containing all votes

$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++;
}


$get_answers = mysql_query("SELECT * FROM answers WHERE poll_id = 1 ");

while($answer = mysql_fetch_assoc($get_answers)) { //loop through all answers

$id = $answer['id']; 
$width = round((int)$votes[$id]/$total_votes*99+1); //100%

echo ' This Answer has ('.(int)$votes[$id].' vote'.((int)$votes[$id] != 1 ? "s":"").')
'; }

我想保留的是$width票数和票数$votes[$id]。如果我提供了答案变量,无论是从数组计算全部还是计算单个答案结果的情况。

我在这里无所适从,我很快就会没有头发,所以如果有帮助,欢迎任何建议/批评。

4

1 回答 1

0
$q = 'SELECT * FROM votes WHERE poll_id = :poll_id';
$params = array(':poll_id' => 1);
$stmt = $db->prepare($q);
$stmt->execute($params);
while ($row = $stmt->fetch()) {

将是转换为 PDO 的非常基本的查询/结果(这只是在 PDO 中执行此操作的一种方法)。你到底有什么问题?PHP 站点上的 PDO 文档非常强大,其中包含大量示例。

你试过什么?什么不工作?您遇到了哪些意外行为或错误?在给出任何真正的答案之前,需要更多关于实际问题的信息。

-- 从评论中编辑 --

您的原始代码应该可以正常工作

while ($row = $stmt->fetch()) {
  $answer_id = $row['answer_id'];
}

应该仍然可以工作,你可以从那里开始。

于 2013-02-27T15:53:47.030 回答