Codeigniter 4 Google Bar Chart Integration Tutorial

Share this Article
Reading Time: 5 minutes
1,557 Views

Inside this article, we will see the concept of CodeIgniter 4 Google Bar Chart Integration. This article will be step by step graph integration.

Bar chart represents the information in very graphical view which provides the complete idea about data. Google charts provides several graphical view. Here, we will use google charts to add Bar chart into CodeIgniter 4 application.

Learn More –

Let’s get started.


CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Environment (.env) Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.


Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

We will use MySQL command to create database. Run this command into Sql tab of PhpMyAdmin.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.


Create Database Table

Next, we need a table. That table will be responsible to store data.

Let’s create table with some columns.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
 `name` varchar(100) NOT NULL COMMENT 'Name',
 `email` varchar(255) NOT NULL COMMENT 'Email Address',
 `contact_no` varchar(50) NOT NULL COMMENT 'Contact No',
 `created_at` varchar(20) NOT NULL COMMENT 'Created date',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Successfully, we have created a table.


Database Connection

Open .env file from project root.

Search for DATABASE. You should see the connection environment variables into it. Put your updated details of database connection string.

 
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = localhost
database.default.database = codeigniter4_app
database.default.username = root
database.default.password = root
database.default.DBDriver = MySQLi
database.default.DBPrefix =
   

Now, database successfully connected with the application.


Import Test Data to Table

Here, we have a simple script to insert some test values into table. Copy code and execute inside created database.

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `name`, `email`, `contact_no`, `created_at`) VALUES
(1, 'Sanjay Kumar', 'sanjay@test.com', '8527419635', '2019-01-01'),
(2, 'Vijay Rohila', 'vijay@net.com', '8529632145', '2019-02-01'),
(3, 'Ashish Kumar', 'ashish@gmail.com', '8956237415', '2018-03-01'),
(4, 'Dhananjay Negi', 'dj@test.com', '9000000004', '2019-04-01'),
(5, 'Pradeep Goyal', 'pradeep@test.com', '8794563215', '2017-05-01'),
(6, 'Monu Thakur', 'monu_thakur@test.com', '8749653215', '2019-06-01'),
(7, 'Prateek', 'prateek@test.com', '7412589632', '2019-07-01'),
(8, 'Raj Kishore', 'raj_kishore@test.com', '9874563215', '2016-08-01'),
(9, 'Deepak Kumar', 'deepak@test.com', '7458963214', '2019-09-01'),
(10, 'Rajan', 'rajan@test.com', '9874563218', '2019-10-01'),
(11, 'Herry', 'herry@test.com', '8526397418', '2019-11-01'),
(12, 'Mark', 'mark@test.com', '9852631478', '2019-12-01');

When you will execute this Sql query into your PhpMyadmin, it will insert dummy rows into users table.


Create Controller

Open project into terminal and run this spark command to create controller.

$ php spark make:controller Chart --suffix

It will create ChartController.php file inside /app/Controllers folder. Open controller file and write this complete code into it.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class ChartController extends BaseController
{
	private $db;

	public function __construct()
	{
		$this->db = \Config\Database::connect();
	}

	public function index()
	{
		$year_wise = $this->db->query("SELECT COUNT(id) as count,YEAR(created_at) as year FROM users GROUP BY YEAR(created_at)")->getResult();

		$data['year_wise'] = $year_wise;

		return view("bar-chart", $data);
	}
}

Create Route

Open Routes.php from /app/Config folder. Add this route into it.

//...

$routes->get('bar-chart', 'ChartController::index');

//...

Create View File

Next, create a view file with name bar-chart.php inside /app/Views folder.

Open bar-chart.php and write this following code into it.

<!Doctype html>
<html>
<head>
  <title>CodeIgniter 4 Google Bar Chart Integration Tutorial</title>
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> 
  <script type="text/javascript">
      google.charts.load('visualization', "1", {
          packages: ['corechart']
      });
  </script>
</head>
<body>
<div class="row">
  <div class="col-md-12">
    <h2 style="text-align:center;">CodeIgniter 4 Google Bar Chart Integration Tutorial</h2>
    <div id="bar_year_wise" style="width: 900px; height: 500px; margin: 0 auto"></div>
  </div>  
</div>
<script>
 
  // Draw the bar chart for registered users year wise
  google.charts.setOnLoadCallback(barChart);
   
  // for
  function barChart() {
 
    /* Define the chart to be drawn.*/
    var data = google.visualization.arrayToDataTable([
        ['Year', 'Users Count'],
        <?php 
         foreach ($year_wise as $row){
         echo "['".$row->year."',".$row->count."],";
         }
         ?>
    ]);
    var options = {
        title: 'Year wise Registered Users Bar Chart',
        is3D: true,
    };
    /* Instantiate and draw the chart.*/
    var chart = new google.visualization.BarChart(document.getElementById('bar_year_wise'));
    chart.draw(data, options);
  }
</script>
</body>
</html>

Application Testing

Open project terminal and start development server via command:

$ php spark serve

URL: http://localhost:8080/bar-chart

We hope this article helped you to learn Codeigniter 4 Google Bar Chart Integration Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.