Creating Dynamic Data Graph using PHP and Chart.js

by Vincy. Last modified on August 25th, 2022.

If we want to visualize statistics, graphs are one of the best ways of representation. Understanding data becomes easy and obvious with the use of graphs. There are various charting libraries like Google Charts, Highcharts, Chart.js and more.

Previously, we have created example code to generate the graph using Highcharts. Let us create an example for creating graph view with the use of Chart.js library.

View Demo

Creating graph view using Chart.js is simple and easy. I have created the graph output for dynamic data retrieved from the database. I have a MySQL database table tbl_marks containing student marks.

I read the mark data and supplied it to the Chart.js function to create the graph with the mark statistics.

This screenshot shows the graph output generated by Chart.js charting library with the dynamic data from the database.

chart-js-dynamic-data-graph-output

 

Chart HTML5 Canvas

Download  Chartjs library from the GitHub and include the library files in your example. In the landing HTML page, I have a HTML5 canvas element to plot the graph output.

On loading the landing page, I send an AJAX request to the PHP to read student marks from the database. This JSON response will be parsed and supplied as the parameter to the Chart.js function to create the graph.

PHP gives limitless support for handling JSON file via programming with its built-in functions.

<!DOCTYPE html>
<html>
<head>
<title>Creating Dynamic Data Graph using PHP and Chart.js</title>
<style type="text/css">
BODY {
    width: 550PX;
}

#chart-container {
    width: 100%;
    height: auto;
}
</style>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>


</head>
<body>
    <div id="chart-container">
        <canvas id="graphCanvas"></canvas>
    </div>

    <script>
        $(document).ready(function () {
            showGraph();
        });


        function showGraph()
        {
            {
                $.post("data.php",
                function (data)
                {
                    console.log(data);
                     var name = [];
                    var marks = [];

                    for (var i in data) {
                        name.push(data[i].student_name);
                        marks.push(data[i].marks);
                    }

                    var chartdata = {
                        labels: name,
                        datasets: [
                            {
                                label: 'Student Marks',
                                backgroundColor: '#49e2ff',
                                borderColor: '#46d5f1',
                                hoverBackgroundColor: '#CCCCCC',
                                hoverBorderColor: '#666666',
                                data: marks
                            }
                        ]
                    };

                    var graphTarget = $("#graphCanvas");

                    var barGraph = new Chart(graphTarget, {
                        type: 'bar',
                        data: chartdata
                    });
                });
            }
        }
        </script>

</body>
</html>

PHP Code to Read Student Marks from MySQL Database

The PHP file data.php is requested via AJAX to access database to read the student marks. After reading the records it returns it as JSON response. The code is,

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

require_once('db.php');

$sqlQuery = "SELECT student_id,student_name,marks FROM tbl_marks ORDER BY student_id";

$result = mysqli_query($conn,$sqlQuery);

$data = array();
foreach ($result as $row) {
	$data[] = $row;
}

mysqli_close($conn);

echo json_encode($data);
?>

View DemoDownload

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “Creating Dynamic Data Graph using PHP and Chart.js”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page