MYSQL查询和Chart.js和PHP

Hoping for some help.

I have data in a MYSQL database containing a listing of computers in the company. One of the fields is the date a computer was purchased, another is the brand.

I want to create a bar chart using Chart.js showing the amount of computers we have for each distinct year. So on the X axis we have all the distinct years as labels and on the Y axis we have the count of all the computers purchased in each one of the years.

I have written this code but can not get it to work:

The Query:

$sql = "SELECT YEAR(purchased) AS years, COUNT(brand) AS 'count' FROM computers GROUP BY purchased, brand ORDER BY purchased";
$result = mysqli_query($conn, $sql);


        $years = array();
        $count = array();
        while ($row = mysql_fetch_assoc($result)) {
            $years[]  = $row["years"];
            $count[] = $row["count"];
        }    
    mysqli_close($conn);

Then the chart:

<script>


    var barChartData = {
        labels : <?php=json_encode($years);?>,
        datasets : [
            {
                fillColor : "rgba(220,220,220,0.5)",
                strokeColor : "rgba(220,220,220,0.8)",
                highlightFill: "rgba(220,220,220,0.75)",
                highlightStroke: "rgba(220,220,220,1)",
                data : <?php=json_encode($count);?>
            }       ]

    }
    window.onload = function(){
        var ctx = document.getElementById("canvas").getContext("2d");
                ctx.canvas.height = 200;
        window.myBar = new Chart(ctx).Bar(barChartData, {
            responsive : true
        });
    }

    </script>

Any ideas to what I am doing wrong. Have struggled to get this to chart.

Thank you.

Your data is set to json_encode, this is not how chart.js can read it.

Change your code from:

<?php=json_encode($count);?>

To:

["<?php echo implode('","',$count);?>"]

And for the years, from:

<?php=json_encode($years);?>

to:

["<?php echo implode('","',$years);?>"]

The quotes are there to contain anything the isn't a numerical value, if your positive that all data is numerical, you can remove them, but since it doesn't hurt to have them, I've included them.

Figured this out:

1: Used this query:

SELECT YEAR(purchased) as years, COUNT(ID) as count FROM computers GROUP BY years

2: Had a TYPO! while ($row = mysql_fetch_assoc($result)) should had been:

while ($row = mysqli_fetch_assoc($result)). I forgot the i in mysql_fetch!

Along with the great help from Greg it is working great now.

Thanks for the help!