PHP CodeIgniter 4 Google Bar And Line Charts Example Tutorial

PHP CodeIgniter Google Line And Bar Charts Tutorial

So many times, a novice person faces trouble while integrating Google Charts in CodeIgniter 4. If this happens with you as well, then you should definitely go through this tutorial completely after which you will be knowing how to get data from the MySQL database and then implement it in the Google Line Chart in Codeigniter. Further, how to add identical data in the CodeIgniter Bar Chart.

CodeIgniter Google Line Chart Example

Many of us may already know that another name of a line chart is a line graph. A Curve Chart shows the data as a series of data points called “markers” which are joined by straight-line portions.


PHP CodeIgniter 4 Google Bar And Line Charts Integration Example

Step 1- Install New CodeIgniter Project

Step 2- Make Database Connection

Step 3- Create Table And Insert Data SQL

Step 4- Formulate New Route

Step 5- Create Chart Controller

Step 6- Add Line Chart In View

Step 7- Start CI Project


Install New CodeIgniter App

In this step, we simply have to install or download the CodeIgniter application. We can do it either by using the composer command for which we have to install the Composer tool:

composer create-project codeigniter4/appstarter


We can also do this by the manual method using the given link for downloading or installing:


Afterward, we will change the default project folder name to “my_ci_app” or some other name.


Make Database Connection

Here, in this step, we will open the app/Config/Database.php for adding data into the chart. Then, inside the default array, we have to enter the database name, username and password:

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'codeigniter_db',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,


Create Table And Insert Data SQL

Since the database connection has been made, so app and DB are now able to communicate.

Now, we will create a table and insert some records into it for the Google Bar and Line Chart in CodeIgniter:

CREATE TABLE `product` (
  `id` int(11) NOT NULL COMMENT 'Primary Key',
  `name` varchar(255) NOT NULL COMMENT 'name',
  `sell` varchar(55) NOT NULL COMMENT 'sell',    
  `created_at` varchar(30) NOT NULL COMMENT 'created at'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Atomic database';

INSERT INTO `product` (`id`, `name`, `sell`, `created_at`) VALUES
(1, 'Coca Cola', '5000', '2021-05-01'),
(2, 'Pepsi', '7000', '2021-05-02'),
(3, 'Coke Zero', '19000', '2 021-05-03'),
(4, 'Pepsi Max', '1500', '2021-05-04'),
(5, 'Diet Coke', '19000', '2021-05-05'),
(6, 'Pepsi Light', '3000', '2021-05-06'),
(7, 'Gatorade', '22000', '2021-05-07');

Formulate New Route

In this step, we would need to open the app/Config/Routes.php and incorporate the controller in the route method and then set up the new route:


$routes->get('/show-google-charts', 'GColumnChartController::initChart');

Create Chart Controller

So, here, we will get into the controllers’ folder and set up a new controller file here, then define the single function inside the controller class.

This function will help in fetching the records from the database using the CodeIgniter 4 SQL queries and passing the retrieved data into the view file.

Further, we will insert the below code inside the app/Controllers/GColumnChartController.php file:


namespace App\Controllers;
use CodeIgniter\Controller;

class GColumnChartController extends Controller

    public function index() {
        return view('chart');
    public function initChart() {
        $db = \Config\Database::connect();
        $builder = $db->table('product');

        $query = $builder->select("COUNT(id) as count, sell as s, DAYNAME(created_at) as day");
        $query = $builder->where("DAY(created_at) GROUP BY DAYNAME(created_at), s")->get();
        $record = $query->getResult();

        $products = [];

        foreach($record as $row) {
            $products[] = array(
                'day'   => $row->day,
                'sell' => floatval($row->s)
        $data['products'] = ($products);    
        return view('chart', $data);                


Create Google Line Chart View

We have to remember to create the chart.php inside the controller folder and inject the complete code in the file.

This file holds the Google chart js and the JavaScript functions and methods to display the line and bar chart in the CodeIgniter app. Then, we will copy the given code and add it into the app/Views/chart.php file:

<!DOCTYPE html>
<html lang="en">

	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Google Bar & Column Charts in Codeigniter</title>
	<link rel="stylesheet" href="[email protected]/dist/css/bootstrap.min.css">


		<div class="container">
			<div class="mb-5 mt-5">
				<div id="GoogleLineChart" style="height: 400px; width: 100%"></div>

			<div class="mb-5">
				<div id="GoogleBarChart" style="height: 400px; width: 100%"></div>

		<script type="text/javascript" src=""></script>
			google.charts.load('current', {'packages':['corechart', 'bar']});

            // Line Chart
			function drawLineChart() {
				var data = google.visualization.arrayToDataTable([
					['Day', 'Products Count'],
							foreach ($products as $row){
							   echo "['".$row['day']."',".$row['sell']."],";
						} ?>

				var options = {
					title: 'Line chart product sell wise',
					curveType: 'function',
					legend: {
						position: 'top'
				var chart = new google.visualization.LineChart(document.getElementById('GoogleLineChart'));
				chart.draw(data, options);
			// Bar Chart
			function drawBarChart() {
				var data = google.visualization.arrayToDataTable([
					['Day', 'Products Count'], 
							foreach ($products as $row){
							   echo "['".$row['day']."',".$row['sell']."],";
				var options = {
					title: ' Bar chart products sell wise',
					is3D: true,
				var chart = new google.visualization.BarChart(document.getElementById('GoogleBarChart'));
				chart.draw(data, options);



Start CI Project

So, all the steps have been completed. Now, we have to test by typing the given command in the console:

php spark serve



So friends, hope that you have learned thoroughly in this tutorial how to integrate Google Line and Bar or Column Charts in CodeIgniter.

It’s quite significant to integrate the Google Charts in your CodeIgniter apps since these are dynamic, interactive and make the data visualization quite impressive.


Leave a Reply

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