how to use chart js in php and mysql code example

Example 1: chart.js - getting data from database using mysql and php

Please place your php code into another file called api.php and use $.ajax to get these data with JSON format. To convert data into JSON format data you should use json_encode() php function.

I have set sample example you can see here.

Please refer below code example:

api.php

$arrLabels = array("January","February","March","April","May","June","July");
$arrDatasets = array('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' => array('28', '48', '40', '19', '86', '27', '90'));

$arrReturn = array(array('labels' => $arrLabels, 'datasets' => $arrDatasets));

print (json_encode($arrReturn));
example.html

$.ajax({
type: 'POST',
url: 'api.php',
success: function (data) {
lineChartData = data;//alert(JSON.stringify(data));
var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Line(lineChartData);

var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {responsive: true});
} 
});
Please note that you should pass value of randomScalingFactor() at api.php.

Please check and let me know if you require any further help.

Example 2: bar chart using chart js in php mysql

CREATE TABLE `tblsales` (  `SalesId` int(11) NOT NULL,  `Product` varchar(90) NOT NULL,  `TotalSales` double NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1; ---- Dumping data for table `tblsales`-- INSERT INTO `tblsales` (`SalesId`, `Product`, `TotalSales`) VALUES(1, 'Surf Powder', 1400),(2, 'Mr. Clean Powder', 800),(3, 'Tide Powder', 5052),(4, 'Ariel Powder', 8030); ---- Indexes for dumped tables-- ---- Indexes for table `tblsales`--ALTER TABLE `tblsales`  ADD PRIMARY KEY (`SalesId`); ---- AUTO_INCREMENT for dumped tables-- ---- AUTO_INCREMENT for table `tblsales`--ALTER TABLE `tblsales`  MODIFY `SalesId` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;

Tags:

Php Example