使用ChartJS和PHP从mySQL数据库中分组条形图

问题描述 投票:1回答:2

index.php - 从mySQL数据库中获取数据

<?php

header('Content-Type: application/json');

$conn = mysqli_connect('localhost', 'root', '', 'registration');

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$query = sprintf("SELECT ratingid, variety, quality FROM chartdata ORDER BY ratingid");

$result = mysqli_query($conn, $query);

$data = array();
foreach ($result as $row) {
    $data[] = $row;
}

mysqli_close($conn);

print json_encode($data);
?>

app.js

     $(document).ready(function(){
     $.ajax({
     url: "http://localhost/mychart4/index.php",
     method: "GET",
     success: function(data) {
      console.log(data);
      var rating = [];
      var variety = [];
      var quality = [];

      for(var i in data) {
        rating.push(data[i].ratingid);
        variety.push(data[i].variety);
        quality.push(data[i]).quality);
      }

      var chartdata = {
        labels: rating,
        datasets: [
          {
            label: 'Red',
            backgroundColor: 'rgba(200, 200, 200, 0.75)',
            borderColor: 'rgba(200, 200, 200, 0.75)',
            hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
            hoverBorderColor: 'rgba(200, 200, 200, 1)',
            data: variety
          },
          {
            label: 'Blue',
            backgroundColor: 'rgba(200, 200, 200, 0.75)',
            borderColor: 'rgba(200, 200, 200, 0.75)',
            hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
            hoverBorderColor: 'rgba(200, 200, 200, 1)',
            data: quality
          }
        ]
      };

      var ctx = $("#mycanvas");

      var barGraph = new Chart(ctx, {
        type: 'bar',
        data: chartdata,
        options: {
          barValueSpacing: 20,
          title: {
                display: true,
                text: 'Variety',
                fontSize: 20
          },
          scales: {
            xAxes: [{
              scaleLabel: {
                display: true,
                labelString: 'Rating options'
              }
            }],
            yAxes: [{
              scaleLabel: {
                display: true,
                labelString: 'Amount'
              },
              ticks: {
                beginAtZero: true
              }
            }]
          }
        }
      });
    },
    error: function(data) {
      console.log(data);
     }
     });
    });

bargaph.html

<!DOCTYPE html>
<html>
  <head>
      <title>ChartJS - BarGraph</title>
      <style type="text/css">
      #chart-container {
        width: 640px;
        height: auto;
      }
    </style>
  </head>
  <body>
    <div id="chart-container">
      <canvas id="mycanvas"></canvas>
    </div>

    <!-- javascript -->
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="js/Chart.min.js"></script>
    <script type="text/javascript" src="js/app.js"></script>
  </body>
</html>

我正在尝试使用ChartJS在mySQL数据库中使用来自多个列(品种,质量)的值来渲染分组条形图。但是,当我打开HTML文件时,浏览器不显示任何内容。我不确定问题是什么,因为条形图在我用一列(品种)尝试时正确呈现。当我打印出由数据形成的JSON数组时,这是输出:

[{"ratingid":"1","variety":"8","quality":"1"},{"ratingid":"2","variety":"1","quality":"9"},{"ratingid":"3","variety":"1","quality":"0"},{"ratingid":"4","variety":"11","quality":"11"},{"ratingid":"5","variety":"1","quality":"1"}]
php mysql json chart.js
2个回答
1
投票

代码中有一个非常小的错误需要删除。

现行代码:

quality.push(data[i]).quality);

更正:

quality.push(data[i].quality);

只需要删除一个额外的')'并且它有效...

Bar Chart


1
投票

完整的工作代码如下;

<!-- index.php  -->

<?php

header('Content-Type: application/json');

$conn = mysqli_connect('localhost', 'root', '', 'registration');

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$query = sprintf("SELECT ratingid, variety, quality FROM chartdata ORDER BY
ratingid");

$result = mysqli_query($conn, $query);

$data = array();
foreach ($result as $row) {
    $data[] = $row;
}

mysqli_close($conn);

print json_encode($data);

//-- app.js

$(document).ready(function () {
    $.ajax({
            url: "http://localhost/test/barChart/index.php",
            method: "GET",
            success: function (data) {
                console.log(data);
                var rating = [];
                var variety = [];
                var quality = [];

                for (var i in data) {
                    rating.push(data[i].ratingid);
                    variety.push(data[i].variety);
                    quality.push(data[i].quality);
            }

            var chartdata = {
                labels: rating,
                datasets: [{
                        label: 'Red',
                        backgroundColor: 'rgb(255, 0, 0)',
                        borderColor: 'rgba(200, 200, 200, 0.75)',
                        hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
                        hoverBorderColor: 'rgba(200, 200, 200, 1)',
                        data: variety
                    },
                    {
                        label: 'Blue',
                        backgroundColor: 'rgb(0, 0, 255)',
                        borderColor: 'rgba(200, 200, 200, 0.75)',
                        hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
                        hoverBorderColor: 'rgba(200, 200, 200, 1)',
                        data: quality
                    }
                ]
            };

            var ctx = $("#mycanvas");

            var barGraph = new Chart(ctx, {
                type: 'bar',
                data: chartdata,
                options: {
                    barValueSpacing: 20,
                    title: {
                        display: true,
                        text: 'Variety',
                        fontSize: 20
                    },
                    scales: {
                        xAxes: [{
                            scaleLabel: {
                                display: true,
                                labelString: 'Rating options'
                            }
                        }],
                        yAxes: [{
                            scaleLabel: {
                                display: true,
                                labelString: 'Amount'
                            },
                            ticks: {
                                beginAtZero: true
                            }
                        }]
                    }
                }
            });
        },
        error: function (data) {
            console.log(data);
        }
    });
});
<!-- bargraph.html -->

<!DOCTYPE html>
<html>
<head>
  <title>ChartJS - BarGraph</title>
  <style type="text/css">
  #chart-container {
    width: 640px;
    height: auto;
  }
</style>
</head>
<body>
<div id="chart-container">
  <canvas id="mycanvas"></canvas>
</div>

<!-- javascript -->
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.