如何正确传递php mysql数据到ChartJs

1bqhqjot  于 2022-11-06  发布在  Chart.js
关注(0)|答案(2)|浏览(148)

我希望能够使用ChartJs生成条形图和饼图。我使用php和mysql来获取数据。我想生成的条形图是一个显示学生统计数据的图表,其中包括男生和女生的统计数据,以及学生总数。下面是一个我希望结果如何显示的示例:

它可能不完全像它,但我觉得它给了一个想法。我的代码问题,我似乎不明白,因为我是一个新手的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);

下面是我从控制台得到的结果:
【{“男”:“5”,“女”:“2”}】
将感谢建议,我如何可以使它更好,并做同样的饼图也。
根据我所做的,这是我的图表的显示方式:

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

sxpgvts3

sxpgvts31#

建议您将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);
      }
    });
unhi4e5o

unhi4e5o2#

我意识到问题出在我的脚本上。非常感谢@milan kumar帮助我完成了查询。我所缺少的是我发送到 AJAX 的数据类型的规范。我所要做的就是在success函数之前添加值为'json'的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]
              }
            ] 
        };
      });

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

相关问题