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

时间:2015-06-19 02:11:36

标签: php mysql chart.js

我尝试将静态数据转换为使用数据库结果。我将使用mysql和php。

这是我的示例代码

    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
    });
}

下面是我的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 );

我如何使用我的mysql查询中的那些计数并将其实现到chartjs上的数据集?我也想从我的mysql查询生成标签。我应该在jquery代码中循环数据集吗?

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

3 个答案:

答案 0 :(得分:5)

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

我已经设置了示例示例,您可以看到here

请参考下面的代码示例:

  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});
    } 
    });
    
  3. 请注意,您应该在randomScalingFactor()传递api.php的值。

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

答案 1 :(得分:4)

首先使用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];
}

在此之下,只需将这些数据结构插入您的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));?>
        }
    ]
}

假设window.onload和canvas元素的HTML都在适当的位置。

答案 2 :(得分:0)

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

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);

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

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:

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