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

后端 未结 3 1625
小蘑菇
小蘑菇 2020-12-01 10:02

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

Example Code:

3条回答
  •  遥遥无期
    2020-12-01 10:26

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

    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.

    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:

    
    

提交回复
热议问题