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

#41756

@rubiconx,

Pushing datapoint values to different arrays & passing them in multi-series chart options should work fine in this case. Please find the code snippet below.


<?php
$dataPoints1 = array();
$dataPoints2 = 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,yval1, yval2 FROM datapoints";

if ($result=mysqli_query($con,$sql)){	  
	foreach($result as $row){
		array_push($dataPoints1, array("x"=> $row["xval"], "y"=> $row["yval1"]));
		array_push($dataPoints2, array("x"=> $row["xval"], "y"=> $row["yval2"]));}
}

mysqli_close($con);
?>

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


Vishwas R
Team CanvasJS