Home forums Using CanvasJS Issues retrievng data from MySql Reply To: Issues retrievng data from MySql

#7499

Anjali
Participant

Andres,

Here is a modified version of our previous example where we generate JSON data using echo statements.

Below is the sample code

1. PHP Service to return JSON Data using echo statements:

<?php

	$conn = new mysqli("127.0.0.1","user","password", "chartDb");

	// Check connection
	if ($conn->connect_error) {
		die("Connection failed: " . $conn->connect_error);
	} else
	{
		$data_points = array();
		
		$result = mysqli_query($conn, "SELECT * FROM pie_chart");

		while($row = mysqli_fetch_array($result))
		{        
			$point = array("label" => $row['Support'] , "y" => $row['yValues']);
			array_push($data_points, $point);        
		}

		//echo json_encode($data_points, JSON_NUMERIC_CHECK);

		// JSON data using echo statements
		
		$length = sizeof($data_points);

		echo "[";
		for ( $i = 0; $i <= $length-1; $i++) { 
			echo "{ \"label\": \"" , $data_points[$i]['label'],"\", \"y\": " , $data_points[$i]['y'], "}";
			if( $i < $length-1)
				echo ",";
		}
		echo "]";	
	}
?>

2. HTML Page to Fetch Data and render Chart

<html>
<head>
<script src="jquery-1.11.1.min.js"></script>
<script src="canvasjs.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
	var dataPoints = [];
        $.getJSON("data.php", function (result) {
            var chart = new CanvasJS.Chart("chartContainer", {
                data: [
                    {
                        type: "pie",
                        dataPoints: result
                    }
                ]
            });
            chart.render();
        });
    });
</script>
</head>
<body>
       <div id="chartContainer" style="width:500px; height: 300px"></div>
</body>
</html>

__
Anjali

  • This reply was modified 2 years ago by  Anjali.