Skip to main content

Creating Dynamic Graphs and Charts with PHP

Are you looking for PHP script to create dynamic Graphs and Charts? You’re here at right place. Here is a detailed tutorial to create dynamic graphs and charts with PHP using FusionCharts library. The library comes along with JavaScript library to build interactive charts and graphs for your applications.

This is a sample database design for charts. The table chart will contain chart details Label and Value.

There is also insert statement to insert few records to run script successfully to create dynamic chart.

So make sure to create a table chart and also insert few records using below table create statement and insert statement.

CREATE TABLE IF NOT EXISTS `chart` (
`Label` varchar(255) NOT NULL,
`Value` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `chart` (`Label`, `Value`) VALUES
('Bakersfield Central', 880000),
('Garden Groove harbour', 730000),
('Los Angeles Topanga', 590000),
('Compton-Rancho Dom', 520000),
('Daly City Serramonte', 330000);

Now we will get data from table chart and create data into JSON format to use because the FusionCharts library needs data in JSON format.
<?php
$query = "
SELECT Label, Value
FROM chart";
$resultset = mysqli_query($conn, $query) or die("database error:". mysqli_error($conn));
$data = array();
while( $rows = mysqli_fetch_assoc($resultset) ) {
$data[] = $rows;
}
$josn_data = json_encode($data);
?>

Needs to add a chart container div with provided id when initializing chart

<div id="my_chart"></div>

Now we will fusioncharts.php and initialize the chart using new FusionCharts() with required chart details to display in chart. We also need to pass $josn_data to create chart from data.
<?php
include("includes/fusioncharts.php");
// Syntax for the constructor - new FusionCharts("type of chart", "unique chart id", "width of chart", "height of chart", "div id to render the chart", "type of data", "actual data")
$columnChart = new FusionCharts("column2d", "ex1", "100%", 400, "my_chart", "json", "{
'chart':{
'caption':'Harrys SuperMart',
'subCaption':'Top 5 stores in last month by revenue',
'numberPrefix':'$',
'theme':'ocean'
},
'data':$josn_data
}");
$columnChart->render();
?>

Demo 

Leave a Reply

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

Shares

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!