Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/260.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何使用PDO MySQL查找投票数_Php_Mysql_Pdo_Count - Fatal编程技术网

Php 如何使用PDO MySQL查找投票数

Php 如何使用PDO MySQL查找投票数,php,mysql,pdo,count,Php,Mysql,Pdo,Count,我有一个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_vote

我有一个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和投票数$voces[$id]。如果我提供了答案变量,则无论是从数组计算全部还是计算单个答案结果

我在这里无所事事,我很快就没有头发了,所以如果有帮助的话,欢迎任何建议/批评

$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'];
}

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

我在这里没有看到尝试的部分,因为PHP本身详细介绍了所需的所有内容……while语句示例在哪里?这就是我正在努力解决的问题好吧,我真正遇到的问题是获取宽度变量和投票数。你写的一切我都做了。正如在准备连接等方面一样,while Parts感谢您!我的代码是一个完全不同的方式,但这似乎更清楚。但是,我已将其转换为一个错误。它不是在数组中循环和存储,你知道为什么吗?它只是进行最后一次已知的投票,并且只进行一次投票。不知道,你需要用新的代码更新问题,让人们看到,否则很难知道问题可能是什么。很好,我把部分代码弄乱了。你的回答对我很有帮助,谢谢