Home Forums Chart Support How can I use PHP MySQL Dynamic data Reply To: How can I use PHP MySQL Dynamic data



Here is how you can display MySQL data in CanvasJS,

1. Create a PHP service that returns data in JSON format.
2. HTML page that does AJAX request to the server and fetches the data. After getting the data, it renders a Chart.

Below is the sample code


1. PHP Service to return JSON Data


header('Content-Type: application/json');

$con = mysqli_connect("","user","password","canvasjssampledb");

// Check connection
if (mysqli_connect_errno($con))
    echo "Failed to connect to DataBase: " . mysqli_connect_error();
    $data_points = array();
    $result = mysqli_query($con, "SELECT * FROM sales");
    while($row = mysqli_fetch_array($result))
        $point = array("label" => $row['product'] , "y" => $row['total_sales']);
        array_push($data_points, $point);        
    echo json_encode($data_points, JSON_NUMERIC_CHECK);


2. HTML Page to Fetch Data and render Chart

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
    <script src="jquery.js"></script>
    <script src="canvasjs.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {

            $.getJSON("data.php", function (result) {

                var chart = new CanvasJS.Chart("chartContainer", {
                    data: [
                            dataPoints: result


    <div id="chartContainer" style="width: 800px; height: 380px;"></div>