Codeigniter 4 Google Pie Chart Integration Tutorial

Share this Article
Reading Time: 6 minutes
309 Views

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

Pie 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 Pie chart into CodeIgniter 4 application.

Learn More –

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed.

Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Turn Development Mode On

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

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.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

Now application is in development mode.


Create Database & Table in Application

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

CREATE DATABASE codeigniter4_app;

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 database and a table. Let’s connect with the application.


Database Connectivity to Application

Open .env file from project root. Search for DATABASE. You should see the connection environment variables.

Let’s set the value for those to connect with database.

 
#--------------------------------------------------------------------
# DATABASE
#-------------------------------------------------------------------- 
 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi
   

Now, database successfully connected with 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("pie-chart", $data);
	}
}

Create Route

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

//...

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

//...

Create View File

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

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

<!Doctype html>
<html>
<head>
  <title>Codeigniter 4 Google Pie Chart Integration Tutorial</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://www.gstatic.com/charts/loader.js"></script>
  <script>
      google.charts.load('visualization', "1", {
          packages: ['corechart']
      });
  </script>
</head>
<body>
<div class="row">
  <div class="col-md-12">
    <h3 style="text-align: center;">Codeigniter 4 Google Pie Chart Integration Tutorial</h3>
    <div id="year_pie" style="width: 900px; height: 500px; margin: 0 auto"></div>
  </div>  
</div>
<script>
  
  // Draw the pie chart for registered users year wise
  google.charts.setOnLoadCallback(yearWiseChart);
   
  // for year wise
  function yearWiseChart() {
 
    /* 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 Pie Chart',
        is3D: true,
    };
    /* Instantiate and draw the chart.*/
    var chart = new google.visualization.PieChart(document.getElementById('year_pie'));
    chart.draw(data, options);
  }
</script>
</body>
</html>

Application Testing

Start development server:

$ php spark serve

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

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

Buy Me a Coffee

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.

Find More on CodeIgniter 4 here