Chart.js - 使用 mysql 和 php 从数据库中获取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30928840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:08:13  来源:igfitidea点击:

Chart.js - Getting data from database using mysql and php

phpmysqlchart.js

提问by nodeffect

I'm trying to convert the static data to using database results. I'll be using MySQLand PHP.

我正在尝试将静态数据转换为使用数据库结果。我将使用MySQLPHP

Example Code:

示例代码:

var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var lineChartData = {
    labels : ["January","February","March","April","May","June","July"],
    datasets : [
        {
            label: "My First dataset",
            fillColor : "rgba(220,220,220,0.2)",
            strokeColor : "rgba(220,220,220,1)",
            pointColor : "rgba(220,220,220,1)",
            pointStrokeColor : "#fff",
            pointHighlightFill : "#fff",
            pointHighlightStroke : "rgba(220,220,220,1)",
            data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
        },
        {
            label: "My Second dataset",
            fillColor : "rgba(151,187,205,0.2)",
            strokeColor : "rgba(151,187,205,1)",
            pointColor : "rgba(151,187,205,1)",
            pointStrokeColor : "#fff",
            pointHighlightFill : "#fff",
            pointHighlightStroke : "rgba(151,187,205,1)",
            data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
        }
    ]
    }
window.onload = function(){
    var ctx = document.getElementById("canvas").getContext("2d");
    window.myLine = new Chart(ctx).Line(lineChartData, {
        responsive: true
    });
}

Below is my php/msql:

下面是我的 php/msql:

$result = mysql_query("SELECT COUNT(*) FROM customer WHERE month='january'") or die(mysql_error());
$row1 = mysql_fetch_array( $result );

$result = mysql_query("SELECT COUNT(*) FROM customer WHERE month='february'") or die(mysql_error());
$row2 = mysql_fetch_array( $result );

$result = mysql_query("SELECT COUNT(*) FROM customer WHERE month='march'") or die(mysql_error());
$row3 = mysql_fetch_array( $result );

How could I use those count()from my MySQL query and implement it to datasets on chartjs? I would also like the labels to be generated from my MySQL query too. Should I loop the datasets inside the jQuery code?

我如何使用count()我的 MySQL 查询中的那些并将其实现到 chartjs 上的数据集?我也希望从我的 MySQL 查询中生成标签。我应该在 jQuery 代码中循环数据集吗?

This is the plugin that I'm using : http://www.chartjs.org/docs/#line-chart-introduction

这是我正在使用的插件:http: //www.chartjs.org/docs/#line-chart-introduction

回答by potatopeelings

First get your data into suitable data structures using PHP

首先使用 PHP 将数据转换为合适的数据结构

$months = array("january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december");
$monthvalues = array();
foreach ($months as $month) {
    $monthvalues[$month] = 0;
}

$result = mysql_query("SELECT month, count(*) FROM customer group by month") or die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
    $monthvalues[$row[0]] = (int)$row[1];
}

Below that, just plug in those data structures into your Javascript

在此之下,只需将这些数据结构插入到您的 Javascript 中

var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var lineChartData = {
    labels : <?=json_encode($months);?>,
    datasets : [
        {
            label: "My First dataset",
            fillColor : "rgba(220,220,220,0.2)",
            strokeColor : "rgba(220,220,220,1)",
            pointColor : "rgba(220,220,220,1)",
            pointStrokeColor : "#fff",
            pointHighlightFill : "#fff",
            pointHighlightStroke : "rgba(220,220,220,1)",
            data : <?=json_encode(array_values($monthvalues));?>
        }
    ]
}

assuming the the window.onload and the HTML for the canvas element are in their proper places.

假设画布元素的 window.onload 和 HTML 位于适当的位置。

回答by AddWeb Solution Pvt Ltd

Please place your php code into another file called api.phpand use $.ajaxto get these data with JSONformat. To convert data into JSON format data you should use json_encode()php function.

请将您的 php 代码放入另一个名为api.php并用于$.ajaxJSON格式获取这些数据的文件中。要将数据转换为 JSON 格式的数据,您应该使用json_encode()php 函数。

I have set sample example you can see here.

我已经设置了示例示例,您可以在此处查看

Please refer below code example:

请参考以下代码示例:

  1. api.php

    $arrLabels = array("January","February","March","April","May","June","July");
    $arrDatasets = array('label' => "My First dataset",'fillColor' => "rgba(220,220,220,0.2)", 'strokeColor' => "rgba(220,220,220,1)", 'pointColor' => "rgba(220,220,220,1)", 'pointStrokeColor' => "#fff", 'pointHighlightFill' => "#fff", 'pointHighlightStroke' => "rgba(220,220,220,1)", 'data' => array('28', '48', '40', '19', '86', '27', '90'));
    
    $arrReturn = array(array('labels' => $arrLabels, 'datasets' => $arrDatasets));
    
    print (json_encode($arrReturn));
    
  2. example.html

    $.ajax({
    type: 'POST',
    url: 'api.php',
    success: function (data) {
    lineChartData = data;//alert(JSON.stringify(data));
    var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Line(lineChartData);
    
    var ctx = document.getElementById("canvas").getContext("2d");
    window.myLine = new Chart(ctx).Line(lineChartData, {responsive: true});
    } 
    });
    
  1. api.php

    $arrLabels = array("January","February","March","April","May","June","July");
    $arrDatasets = array('label' => "My First dataset",'fillColor' => "rgba(220,220,220,0.2)", 'strokeColor' => "rgba(220,220,220,1)", 'pointColor' => "rgba(220,220,220,1)", 'pointStrokeColor' => "#fff", 'pointHighlightFill' => "#fff", 'pointHighlightStroke' => "rgba(220,220,220,1)", 'data' => array('28', '48', '40', '19', '86', '27', '90'));
    
    $arrReturn = array(array('labels' => $arrLabels, 'datasets' => $arrDatasets));
    
    print (json_encode($arrReturn));
    
  2. 示例.html

    $.ajax({
    type: 'POST',
    url: 'api.php',
    success: function (data) {
    lineChartData = data;//alert(JSON.stringify(data));
    var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Line(lineChartData);
    
    var ctx = document.getElementById("canvas").getContext("2d");
    window.myLine = new Chart(ctx).Line(lineChartData, {responsive: true});
    } 
    });
    

Please note that you should pass value of randomScalingFactor()at api.php.

请注意,您应该传递randomScalingFactor()at值api.php

Please check and let me know if you require any further help.

如果您需要任何进一步的帮助,请检查并告诉我。

回答by Michael

This is based on the answer above with a couple of changes.

这是基于上面的答案,并进行了一些更改。

php:

php:

include 'db.php';
$query = "SELECT month, COUNT(*) count FROM customer WHERE month='march' GROUP BY month";

if ($stmt = $conn->prepare($query)) {
    $stmt->execute();
    $stmt->bind_result($month, $count);            

    $labels = array();
    $data = array();

    while ($stmt->fetch()) {
        $labels[] = $month;
        $data[] = $count;
    }
        $stmt->close();
}

$datasets = array('label'=>"timer",'data'=> $data);
$data = array('labels'=>$labels, 'datasets'=> array($datasets));

echo json_encode($data);

I had to use JSON.pare() on the passed-in array.

我不得不在传入的数组上使用 JSON.pare()。

Javascript:

Javascript:

$.ajax({
    type: 'POST',
    url: 'api.php ',
    datatype: 'json',
    success: function (result) {
        var ctx = document.getElementById("chart").getContext("2d");
        var mychart = new Chart(ctx,
        {
            type: 'bar',
            data: JSON.parse(result),
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: true
                        }
                    }]
                }
            }
        })
    }
})

html:

html:

<canvas id="chart" width="200" height="200"></canvas>