canvas.js饼图从mysql获取数据

时间:2018-07-23 05:24:09

标签: php mysql canvasjs

$con = mysqli_connect("localhost","root","","final_osa");

if (mysqli_connect_errno($con))
{
    echo "Failed to connect to DataBase: " . mysqli_connect_error();
}else
{
    $data_points = array();

    $result = mysqli_query($con, "SELECT * FROM scholars_list");

    while($row = mysqli_fetch_array($result))
    {        
        $point = array("label" => $row['course'], "y" => $row['student_name']);

        array_push($data_points, $point);        
    }

    echo json_encode($data_points, JSON_NUMERIC_CHECK);
}
mysqli_close($con);

我如何制作饼状图,以使某课程中有多少学生入学?谢谢

这是我的JS     $(document).ready(function(){

            $.getJSON("data.php", function (result) {

                var chart = new CanvasJS.Chart("chartContainer", {
                    animationEnabled: true,
                    exportEnabled: true,
                    data: [
                        {
                            type: "pie",
                            showInLegend: "true",
                            legendText: "{label}",
                            indexLabelFontSize: 16,
                            indexLabel: "{label} - #percent%",
                            yValueFormatString: "฿#,##0",
                            dataPoints: result
                        }
                    ]
                });

                chart.render();
            });
        });

1 个答案:

答案 0 :(得分:0)

格式化这样的数据

假设$ records中有您的数据:

$data=array();
foreach ($records as $record) {
    $data[] = array(
        "label"=>$record["student_name"],
        "y"=>$record['course'], //percentage value
    );
}
echo json_encode($data);

Js部分:

var chart = new CanvasJS.Chart("chartContainer", {
                title:{
                    text: "Monthly User work details"              
                },
                data: [              
                {
                    // Change type to "doughnut", "line", "splineArea", etc.
                    type: "pie",
                    showInLegend: "true",
                    legendText: "{label}",
                    indexLabelFontSize: 16,
                    indexLabel: "{label} - #percent%",
                    yValueFormatString: "฿#,##0",
                    dataPoints: JSON.parse(result)
                }
                ]
            });
            chart.render();