Subscribe For Free

Friday, February 23, 2018

Google Column Charts with PHP and MySQL

Populating column charts with google api is one of the simplest way to do. here we are showing 
you a simple example to generate column chart with real time data. fetching data from database table.

Here is the sample code.
PHP Code: Includes connecting to database and fetching data from database table.
$DatabaseServer = "localhost";
$DatabaseUsername = "root";
$DatabasePassword = "root";
$DatabaseName = "demo";

$Connection = mysqli_connect($DatabaseServer, $DatabaseUsername, $DatabasePassword, $DatabaseName);

if ($Connection === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());

$selectsql = "SELECT * FROM graph";
$result = mysqli_query($Connection, $selectsql);    
HTML and Javascript code uses the data from database fetched by php code and google api
to populate column chart
    <script type="text/javascript" src=""></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['bar']});

      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Year', 'Sales', 'Expenses', 'Profit'],
    <?php while($row = mysqli_fetch_array($result)){ ?>
          ['<?php echo $row['name'];?>', 
    <?php echo $row['value1'];?>, 
    <?php echo $row['value2'];?>, 
    <?php echo $row['value3'];?>],
    <?php } ?>

        var options = {
          chart: {
            title: 'Company Performance',
            subtitle: 'Sales, Expenses, and Profit: 2014-2017',

        var chart = new google.charts.Bar(document.getElementById('columnchart_material'));

        chart.draw(data, google.charts.Bar.convertOptions(options));
    <div id="columnchart_material" style="width: 800px; height: 500px;"></div>

Run these queries in your database.
CREATE TABLE `graph` (
  `id` int(2) NOT NULL,
  `name` varchar(34) NOT NULL,
  `value1` int(12) NOT NULL,
  `value2` int(12) NOT NULL,
  `value3` int(12) NOT NULL
INSERT INTO `graph` (`id`, `name`, `value1`, `value2`, `value3`) VALUES
(1, '2014', 11, 2, 7),
(2, '2015', 2, 5, 9),
(4, '2016', 20, 9, 15),
(5, '2017', 14, 21, 5),
(6, '2018', 7, 17, 6);

Everything about column chart

Google Pie Charts with PHP and MySQL
Everything about google pie chart


click it