Home Forums Chart Support using database data to draw charts Reply To: using database data to draw charts



You can retrieve the data points from the database and pass it on chart options as shown in below code snippet.

$dataPoints = array();

$con=mysqli_connect("localhost","root","","test"); //mysqli_connect("host","username","password","db"); - Refer https://www.w3schools.com/php/func_mysqli_connect.asp for more info

if (mysqli_connect_errno()) {
	echo "Failed to connect to MySQL: " . mysqli_connect_error();
$sql="SELECT xval,yval FROM datapoints";

if ($result=mysqli_query($con,$sql)){	  
	foreach($result as $row){
		array_push($dataPoints, array("x"=> $row["xval"], "y"=> $row["yval"]));


window.onload = function () { 
	var chart = new CanvasJS.Chart("chartContainer", {
		animationEnabled: true,
		exportEnabled: true,
		theme: "light1", // "light1", "light2", "dark1", "dark2"
        exportEnabled: true,
			text: "PHP Column Chart from Database - MySQLi"
		data: [{
			type: "column", //change type to bar, line, area, pie, etc  
			dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
	<div id="chartContainer" style="height: 360px; width: 50%; margin: auto;"></div>
	<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>

Please take a look at this Sample Project for complete working sample.

PHP Column Chart from Database - MySQLi

Vishwas R
Team CanvasJS