We know that Google chart basically displays different statistical data on different chart types such as column chart, bar chart, line chart, pie chart etc. You can have a look at the URL https://developers.google.com/chart/ for more information.

In my previous tutorial https://www.roytuts.com/google-chart-using-codeigniter/ the year value was always showing as 2k for 2010, 2011, 2012 etc. Now I have updated the code a little bit so that it will show the exact year on horizontal axis.

You can integrate Google chart with any server side technology but here I will show you how to integrate Google chart with Codeigniter. This tutorial shows step by step so that we can understand how it happens. It displays the data for Company Performance for last five years in bar(column) chart. You can also use other charts for any purpose. In this example I have used data coming from database. You can change the source of data as per your requirements.

If you have any query please feel free to leave a comment.
Prerequisites

    Netbeans 8.1
    XAMPP in Windows
    Codeigniter 3.0.6

Configure XAMPP and Netbeans

From Netbeans IDE go to Tools->Options. Click on PHP. Now on tab “General” browse the file for “PHP 5 Interpreter”. The php interpreter file generally placed inside the <physical drive in Windows OS>:xamppphpphp.exe

Configure Codeigniter and Netbeans

Create a new PHP project in Netbeans. Then remove the index.php file from the newly created project. Now copy the extracted files from Codeigniter 3.0.6 to the newly created project directory.

Directory Structure

A typical directory structure for the project would be as shown below. Here assests directory will contain static resources like css, js, images.

codeigniter join

Final Output

When Chart rendered on view

google column chart

When you mouse hover on Chart slices

google column chart

Now we will see how it happens step by step.

Step 1. Now modify <root directory>/application/config/autoload.php file for auto-loading html, url, file, form and session

$autoload['helper'] = array('html', 'url', 'file', 'form');

$autoload['libraries'] = array('database', 'session');

Step 2. Now modify <root directory>/application/config/config.php file to define encryption key

$config['encryption_key'] = '2d8+e6]K0?ocWp7&`K)>6Ky"|.x|%nuwafC~S/+6_mZI9/17y=sKKG.;Tt}k';

Step 3. Go to location ci/application/config/database.php file and change database parameter values for below parameters

$db['default']['username'] = 'root'; //your database username
$db['default']['password'] = ''; //your database password
$db['default']['database'] = 'codeigniter'; //your MySQL database name

Step 4. Create a MySQL table in “cdcol” database

CREATE TABLE `performance` (
  `performance_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `performance_year` smallint(4) unsigned NOT NULL,
  `performance_sales` int(10) unsigned NOT NULL,
  `performance_expense` double NOT NULL,
  `performance_profit` double NOT NULL,
  PRIMARY KEY (`performance_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

Step 5. Dump some values into database table – performance

insert  into `performance`(`performance_id`,`performance_year`,`performance_sales`,`performance_expense`,`performance_profit`) values
(1,2010,1000,400,200),
(2,2011,1100,450,220),
(3,2012,760,1120,400),
(4,2013,1030,540,310),
(5,2014,850,420,260),
(6,2015,1250,560,330),
(7,2016,1450,600,360);

Step 6. Create a model file chartmodel.php under ci/application/models directory with the below source code

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Description of BlogModel
 *
 * @author https://www.roytuts.com
 */
class ChartModel extends CI_Model {

    private $performance = 'performance';

    function __construct() {
        
    }

    function get_chart_data() {
        $query = $this->db->get($this->performance);
        $results['chart_data'] = $query->result();
        $this->db->select_min('performance_year');
        $this->db->limit(1);
        $query = $this->db->get($this->performance);
        $results['min_year'] = $query->row()->performance_year;
        $this->db->select_max('performance_year');
        $this->db->limit(1);
        $query = $this->db->get($this->performance);
        $results['max_year'] = $query->row()->performance_year;
        return $results;
    }

}

Step 7. Create a controller file chartcontroller.php under ci/application/controllers with the following source code

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Description of Blog
 *
 * @author https://www.roytuts.com
 */
class ChartController extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('chartmodel', 'chart');
    }

    public function index() {
        $results = $this->chart->get_chart_data();
        $data['chart_data'] = $results['chart_data'];
        $data['min_year'] = $results['min_year'];
        $data['max_year'] = $results['max_year'];
        $this->load->view('line_chart', $data);
    }

}

Step 8. Create a view file line_chart.php under ci/application/views

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8"/>
        <title></title>
        <!-- Load Google chart api -->
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript">
            google.load("visualization", "1.1", {packages: ['bar', 'timeline']});
            google.setOnLoadCallback(drawChart);
            function drawChart() {
                var data = google.visualization.arrayToDataTable([
                    [{type: 'string', label: 'Year'}, {type: 'number', label: 'Sales'}, 'Expenses', 'Profit'],
<?php
foreach ($chart_data as $data) {
    echo '[' . $data->performance_year . ',' . $data->performance_sales . ',' . $data->performance_expense . ',' . $data->performance_profit . '],';
}
?>
                ]);

                var options = {
                    chart: {
                        title: 'Company Performance',
                        subtitle: 'Sales, Expenses, and Profit: <?php echo $min_year . '-' . $max_year; ?>'
                    }
                };

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

                chart.draw(data, options);
            }
        </script>
    </head>
    <body>        
        <div id="columnchart_material" style="width: 900px; height: 500px;"></div>
    </body>
</html>

Step 9. Modify file ci/application/config/routes.php file

$route['default_controller'] = "chartcontroller";

Step 10. If everything is fine then run the application. You will get the output in the browser.

That’s all. Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

1 thought on “Google column chart using Codeigniter

Leave a Reply

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