尝试分离循环结果

时间:2014-02-24 07:04:18

标签: php

我正在进行民意调查,我有一个PHP脚本来获取该民意调查选项投票数的百分比。当我运行查询时,我只是为选项保持0。我怎样才能使每个$ val1根据数据库中的行总数具有不同的数字?

例如:民意调查选项1有1票,民意调查选项2有1票,民意调查选项3有0,民意调查选项4有0.而查询将输出50选项1和选项2和0用于选项3和4

我的代码

       $poll = $db->fetch("SELECT * FROM home_poll ORDER BY id DESC LIMIT 1");
   $option_sql = $db->query("SELECT total FROM home_polls_option WHERE poll_id = '" . $poll['id'] . "'");

        while ($row = mysqli_fetch_array($option_sql)) {
            $val1 = $row['total'];
        }

$poll_votess = $db->query("SELECT * FROM home_polls_vote WHERE poll_id = '" . $poll['id'] ."'");

$val2 = $poll_votess->num_rows;

$res = round ($val1 / $val2 * 100);
 $options1 .= ' <script>

    var doughnutData = [
            {
                value: ' . $res . ',
                color:"#F7464A"
            },
            {
                value : ' . $res . ',
                color : "#46BFBD"
            },
            {
                value : ' . $res . ',
                color : "#FDB45C"
            },
            {
                value : '. $res.',
                color : "#949FB1"
            }

        ];

var myDoughnut = new Chart(document.getElementById("canvas").getContext("2d")).Doughnut(doughnutData);

</script>';

数据库:

home_polls_vote:http://prntscr.com/2vd1lt home_polls_option:http://prntscr.com/2vd1k7

2 个答案:

答案 0 :(得分:0)

在while循环中你已经获得了$val1最新的行值,因为它是0票,你到处都是0.你需要把它放到数组中,然后再使用$res作为数组因此,您可以在脚本中打印不同的值。

编辑:

你可以尝试这样的事情。首先获取总投票数,然后将结果中的百分比放入while循环中。

$poll = $db->fetch("SELECT * FROM home_poll ORDER BY id DESC LIMIT 1");
$option_sql = $db->query("SELECT total FROM home_polls_option WHERE poll_id = '" . $poll['id'] . "'");
$poll_votess = $db->query("SELECT * FROM home_polls_vote WHERE poll_id = '" . $poll['id'] ."'");

$number_of_votes= $poll_votess->num_rows;

while ($row = mysqli_fetch_array($option_sql)) {
    $res[] = round ($row['total'] / $number_of_votes * 100);
}

$options1 .= '<script>

    var doughnutData = [
            {
                value: ' . $res[0] . ',
                color:"#F7464A"
            },
            {
                value : ' . $res[1] . ',
                color : "#46BFBD"
            },
            {
                value : ' . $res[2] . ',
                color : "#FDB45C"
            },
            {
                value : '. $res[3].',
                color : "#949FB1"
            }

        ];

var myDoughnut = new Chart(document.getElementById("canvas").getContext("2d")).Doughnut(doughnutData);

</script>';

答案 1 :(得分:0)

使用mysql进行计算,这将避免多行代码并易于处理

http://dev.mysql.com/doc/refman/5.0/en/precision-math-rounding.html https://dev.mysql.com/doc/refman/5.0/en/case.html

$sql = " SELECT ROUND(COUNT(hpv.id)/hpo.total * 100) AS res 
            FROM  home_polls_option AS hpo
            JOIN home_polls_vote AS hpv ON hpv.poll_id = hpo.poll_id
            WHERE hpv.poll_id=$poll ['id']
            GROUP BY hpo.value";