Using PDO the main file to display column / bar Chart.
Using CSV (Comma Separated Value) file :
File Name
Details
index-csv.php
Reading CSV file by using fgetcsv() and display chart.
chart_data_column.csv
Comma separated value ( csv ) file with data.
Download Zip file at end of this tutorial.
Column Chart : Orientation is vertical Bar Chart : Orientation is horizontal
Column & Bar Chart with data from MySQL database table using PHP pdo and google chart library
Sample column Chart in html
Without using PHP or MySQL, you can try this simple HTML and JavaScript code to display the above column chart. Copy this code and save ( open ) as HTML file. Google Chart library is also included inside the code.
Any one method either MySQLi ( Above code ) or PDO ( Below code ) is to be used to collect data and create the JavaScript array. Both scripts are available inside zip file at the end of this page.
Before displaying records in a table we have created an array in PHP ( $php_data_array). While displaying the records in a table we store each record inside the PHP array.
$php_data_array[] = $row; // Adding to array
After displaying all the records in a table we have the $php_data_array with all the data collected from MySQL table. We can display the Json string like this.
echo json_encode($php_data_array);
We created the PHP array $php_data_array by using MySQL database as source. Once the php array is created the rest of the code remain same. Below you can find code to create this $php_data_array by using csv file as source.
3 : Transferring data from PHP to JavaScript to create the chart
We can show the chart inside a <DIV> tag and place the same any where we want to display the chart.
<div id="chart_div"></div>
The chart drawn above can be displayed with live internet connection as the library is to be loaded from gstatic.com
Data is collected from MySQL database table so data can be edited by using script and the same will be reflected by the Chart. We have not included this part in the present script and there are many tutorials available here one handling data using PHP and MySQL.
You can read tutorials on other types of charts displayed by using data from database.
/*
var chart =
new google.visualization.ColumnChart(document.getElementById('chart_div'));
*/
var chart =
new google.visualization.BarChart(document.getElementById('chart_div'));
Using CSV file as data source
Once the php aray $php_data_array is created the rest of the code remain same. Here we are reading the chart_data_column.csv file to create the $php_data_array. Once the array is created same code can be used. Zip file below contains the chart_data_column.csv file as data source and the index-csv.php file to display the chart.
We used fgetcsv() to read csv file