Home forums Using CanvasJS How can I use PHP MySQL Dynamic data Reply To: How can I use PHP MySQL Dynamic data

#3669

Sunil Urs
Keymaster

Naveen,

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

<?php

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

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

// Check connection
if (mysqli_connect_errno($con))
{
    echo "Failed to connect to DataBase: " . mysqli_connect_error();
}else
{
    $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);
}
mysqli_close($con);

?>

2. HTML Page to Fetch Data and render Chart

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title></title>
    <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
                        }
                    ]
                });

                chart.render();
            });
        });
    </script>
</head>
<body>

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

</body>
</html>