chartJs with MySQL and PHP

chartJs with MySQL and PHP

本文关键字:PHP and MySQL with chartJs      更新时间:2023-09-26

我正在尝试与chartJs进行在线聊天。

我想使用php将MySQL数据推送到chartJs。

MySQL表

id  | page_views | visitors | month |
------------------------------------| 
1   |   200      |   20     | Jan   |
2   |   100      |   10     | Feb   |
3   |   500      |   30     | March |
------------------------------------|

chartJs

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

我想为此应用MySQL循环。

有人能给我举个简单的例子吗?

ChartJS采用JSON格式的数据。

您可以使用AJAX获取JSON数据。

var jsonData = $.ajax({
    url: 'http://yourdomain.com/yourfile.php',
    dataType: 'json',
}).done(function (results){

在调用PHP文件中,您可以对逻辑和数据库访问进行编程。然后,您可以使用json_encode回显数据,以JSON格式输出数组。

header('Content-Type: application/json');
echo json_encode($dataArray);

然后,您可以将数据添加到图表中,如下所示:

var myChart = new Chart(ctx).Line(jsonData);