如何正确地将php mysql数据传递给ChartJs

时间:2017-04-06 09:59:25

标签: javascript php mysql charts chart.js

我希望能够使用ChartJs生成条形图和饼图。我使用php和mysql来获取数据。我想要制作的条形图是一张图表,显示了男性或女性学生的统计数据以及学生总数。以下是我希望结果显示的示例:

enter image description here

它可能不完全像它,但我觉得它给出了一个主意。我的代码问题似乎无法理解,因为我是ChartJs的新手而且只是尝试一下,因为morris.js并没有得到完全的支持。以下是我的代码的外观:

HTML

<div class="box box-success">
        <div class="box box-header with-border">
          <h3 class="box-title">Student Chart</h3>
          <div class="box-tools pull-right">
            <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
            </button>
            <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
          </div>
          <div class="box-body">
            <canvas id="mycanvas" style="height:230px;"></canvas>
          </div>
        </div>

脚本:

$.ajax({
      url: 'data.php',
      type: 'GET',
      success:function(data){
        console.log(data);

        var male = [];
        var female = [];

        for(var count in data){
          male.push(data[count].male);
          female.push(data[count].female);
        }

        var chartdata = {
            labels: male,
            datasets: [
              {
                label: 'Student Gender',
                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:female
              }
            ] 
        };

        var ctx = $('#mycanvas');

        var barGraph = new Chart(ctx, {
          type:'bar',
          data: chartdata
        });
      },
      error:function(data){
        console.log(data);
      }
    });

data.php

$query = "SELECT  
            SUM(CASE WHEN gender = 'Male' THEN 1 ELSE 0 END) as Male,
            SUM(CASE WHEN gender = 'Female' THEN 1 ELSE 0 END) as Female
          FROM students";

$output = array();

if ($result = mysqli_query($connection, $query)) {
    # code...
    foreach ($result as $row) {
        # code...
        $output[] = $row;
    }
} else {
    die("There was a problem". mysqli_error($connection));
}

echo json_encode($output);

以下是我从控制台获得的结果:

[{&#34;男性&#34;:&#34; 5&#34;&#34;女&#34;:&#34; 2&#34;}]

对于我如何能够做得更好并且也为饼图做同样的事情,我们会感激不尽。

根据我所做的事情,这是我的图表显示方式:

enter image description here

注意请忽略照片上的频率。

2 个答案:

答案 0 :(得分:1)

建议您将sql查询更改为以下内容。

$query = "select gender,count(gender) as count from students group by gender";
$output = array();

if ($result = mysqli_query($connection, $query)) {
    # code...
    foreach ($result as $row) {
        # code...
        $output[] = $row;
    }
} else {
    die("There was a problem". mysqli_error($connection));
}

echo json_encode($output);

脚本:

$.ajax({
      url: 'data.php',
      type: 'GET',
      success:function(data){
        console.log(data);

        var gender = [];
        var sum = [];

        for(var count in data){
          gender.push(data[count].gender);
          sum.push(data[count].total);
        }

        var chartdata = {
            labels: gender,
            datasets: [
              {
                label: 'Student Gender',
                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:sum
              }
            ] 
        };

        var ctx = $('#mycanvas');

        var barGraph = new Chart(ctx, {
          type:'bar',
          data: chartdata
        });
      },
      error:function(data){
        console.log(data);
      }
    });

答案 1 :(得分:0)

我意识到问题出在我的脚本上。非常感谢@milan kumar帮助查询。缺少的是我发送给ajax的数据类型的规范。我所要做的就是添加带有值&#39; json&#39;的 dataType 。在成功功能之前,它完美地运作。这就是代码的外观:

脚本:

$.ajax({
      url: 'data.php',
      type: 'GET',
      // this was what I needed to make it work.
      dataType: 'json',
      success:function(data){

        var gender = [];
        var sum = [];

        for(var i in data){
          gender.push(data[i].gender);
          sum.push(data[i].total);
        }

        var ChartData = {
            labels: ['Student Gender'],
            datasets: [
              {
                label: gender[0],
                fillColor: "rgba(210, 214, 222, 1)",
                strokeColor: "rgba(210, 214, 222, 1)",
                pointColor: "rgba(210, 214, 222, 1)",
                pointStrokeColor: "#c1c7d1",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data:sum[0]
              },
              {
                label: gender[1],
                fillColor: "rgba(60,141,188,0.9)",
                strokeColor: "rgba(60,141,188,0.8)",
                pointColor: "#3b8bba",
                pointStrokeColor: "rgba(60,141,188,1)",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(60,141,188,1)",
                data:sum[1]
              }
            ] 
        };
      });

我添加了一些可选属性来美化我的图表。