CodeIgniter 4 Google Pie Chart Integration Example Tutorial

Last Updated on by in CodeIgniter

PHP Codeigniter 4 Google Pie Chart integration tutorial; Fetching data from the database and insert into the pie chart seems tough to you?

Don’t worry; in this example of the Codeigniter google pie chart, we will show more assertive instructions, which will assist you in assimilating the Codeigniter PHP Google pie chart notion practically.

Are you looking for the perfect solution to deal with Pie Chart in the Codeigniter 4 application?

Your wait is over; in this tutorial, we will study how to add a Google Pie chart in the Codeigniter app, display the data from the MySQL database, and display sales figure in the google pie chart.

A pie chart is a circular analytical graphic distributed into slices to demonstrate numerical proportion. In a pie chart, the arc length of each slice is proportional to the volume it portrays.

How to Add Pie Chart in PHP Codeigniter 4 using Google Chart Js

  • Step 1: Install New Codeigniter App
  • Step 2: Make Database Connection
  • Step 3: Create Table & Insert Data
  • Step 4: Create Chart Controller
  • Step 5: Create New Route
  • Step 6: Add Chart in View
  • Step 7: Start CI Project

Install New Codeigniter App

In the starting, you have to install or download the app, and you can do it either by running the composer command:

composer create-project codeigniter4/appstarter

Or you can manually download the codeigniter the app using the given link.

Right after that change the default project folder name to “my_ci_app” or anything fancy you want.

Make Database Connection

In order to add data into the chart, open the app/Config/Database.php, register your database name, username and password into the default array for smooth database connection.

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 & Insert Data

Start the localhost server or real server, move to PHPMyAdmin dashboard, then jump on to the SQL query tab, and execute the following command.

It will concurrently create a table and insert dummy data into the database.

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', '2021-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');

Create Chart Controller

You need a controller file to connect to the database table and write the Codeigniter SQL query to fetch the records based on the day and sales.

First create the controller file, thereafter insert the recommended 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 New Route

Routes handle the request defined in the controller, make sure to open the app/Config/Routes.php, and add the new routes as suggested.

 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------

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

Build Pie Char View File

Next, you need to create the view file, where you will constitute the pie chart using the google chart js, bootstrap and most importantly the data coming from the database.

Create the view file and copy below code and add 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>Codeigniter Google Pie Charts Demo</title>
	<link rel="stylesheet" href="">


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

		<script type="text/javascript" src=""></script>
			google.charts.load('visualization', "1", {
				packages: ['corechart']

			// Pie Chart
			function drawBarChart() {
				var data = google.visualization.arrayToDataTable([
					['Day', 'Products Count'], 
							foreach ($products as $row){
							   echo "['".$row['day']."',".$row['sell']."],";
				var options = {
					title: ' Pie chart data',
					is3D: true,
				var chart = new google.visualization.PieChart(document.getElementById('GooglePieChart'));
				chart.draw(data, options);

Start CI Project

All formalities have been done, now comes the testing time, use php spark command to summon the development server.

php spark serve

Here is the url which will allow you to see the pie chart integration.


Codeigniter 4 Google Pie Chart Integration Example


We managed to create an interactive, dynamic, and data-driven pie chart in Codeigniter and MySQL, with the lethal combination of google chart js open source technology.

Regardless, you never created something like before, but this quick guide described how to work with dynamic google charts in Codeigniter.

You won’t find it difficult to create a simple pie chart module in Codeigniter app from now on.

Digamber - Author

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.