Chart.js - 无法通过PHP从MySQL获取结果

时间:2016-11-02 08:16:31

标签: javascript php mysql chart.js

我试图通过ChartJS插件使用我的MySQL数据库中的数据填充图表,但在这样做时我遇到了

  

mysqli_fetch_assoc():无法在...中获取mysqli_result

error.Since我使用的是json_encode,我试图调整fetch数组,但似乎无法解决这个问题。

非常感谢任何帮助。

    <div class="box-body">
      <div class="chart">

        <canvas id="canvas_bar" style="height:250px"></canvas>

        <?php
        // Start MySQLi connection
        $db = new MySQLi($dbhost,$dbuser,$dbpass,$dbname);
        if ($db->connect_errno) { echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error; }

        // count all records per month
        $sql = "SELECT LOWER(MONTHNAME(mod_date)) AS mdate, count(*) AS cnt FROM qci_modreport GROUP BY LOWER(MONTHNAME(mod_date))";

        if (!($result)) {
            print "ERROR, something wrong with the query.";
        } else {
            $output = array();

            while ($row = mysqli_fetch_assoc($result)) {
                $output[$row['mdate']] = $row['cnt'];
            }
            print (json_encode($output));
        }
        ?>

        <!-- chartJS 1.0.1-->
        <!-- <script src="./plugins/chartjs/Chart.js"></script> -->
        <script src="../../plugins/chartjs/Chart.min.js"></script>  
        <script>
            var barChartData = {
                labels: <?php echo json_encode(array_keys($output)); ?>,
                datasets: [
                        {
                            fillColor: "#03586A", //rgba(151,187,205,0.5)
                            strokeColor: "#03586A", //rgba(151,187,205,0.8)
                            highlightFill: "#066477", //rgba(151,187,205,0.75)
                            highlightStroke: "#066477", //rgba(151,187,205,1)
                            data: <?php echo json_encode(array_values($output)); ?>
                }]
            };
                $(document).ready(function () {
                    new Chart($("#canvas_bar").get(0).getContext("2d")).Bar(barChartData, {
                        tooltipFillColor: "rgba(51, 51, 51, 0.55)",
                        responsive: true,
                        barDatasetSpacing: 6,
                        barValueSpacing: 5
                    });
                });



        </script>

      </div>
    </div>
    <!-- /.box-body -->

1 个答案:

答案 0 :(得分:1)

$result未定义。你应该使用

if (!($result = $db->query($sql1))) { ...

$result = $db->query($sql1);

并且只在你做完之后

if (!$result) { ...

while ($row = mysqli_fetch_assoc($result)) { ...