sql >> Base de Datos >  >> RDS >> Mysql

Chart.js - Obtener datos de la base de datos usando mysql y php

Primero coloque sus datos en estructuras de datos adecuadas usando 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];
}

Debajo de eso, simplemente conecte esas estructuras de datos en su 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));?>
        }
    ]
}

asumiendo que window.onload y el HTML para el elemento canvas están en sus lugares correctos.