Pie Chart Integration with CodeIgniter 4 – HighCharts Js

Reading Time: 6 minutes

Inside this article, we will see the concept of Pie Chart Integration with CodeIgniter 4. 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. We will use jQuery Highcharts to add Pie chart into CodeIgniter 4 application.

To Learn about Bar Chart Integration in CodeIgniter 4 using jQuery Highchart, Click here.

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 `browser_stats` (
 `name` varchar(30) NOT NULL,
 `total_usage` float NOT NULL,

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 values.


database.default.hostname = localhost
database.default.database = codeigniter4_app
database.default.username = admin
database.default.password = admin
database.default.DBDriver = MySQLi
database.default.DBPrefix =
database.default.port = 3306

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 `browser_stats`

INSERT INTO `browser_stats` (`id`, `name`, `total_usage`) VALUES
(1, 'Chrome', 64.02),
(2, 'Firefox', 12.55),
(3, 'IE', 8.47),
(4, 'Safari', 6.08),
(5, 'Edge', 4.29),
(6, 'Others', 4.59);

Create Model

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

$ php spark make:model Browser --suffix

It will create BrowserModel.php at /app/Models folder.

Open BrowserModel.php and write this code.


namespace App\Models;

use CodeIgniter\Model;

class BrowserModel extends Model
	protected $DBGroup              = 'default';
	protected $table                = 'browser_stats';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = [

	// Dates
	protected $useTimestamps        = false;
	protected $dateFormat           = 'datetime';
	protected $createdField         = 'created_at';
	protected $updatedField         = 'updated_at';
	protected $deletedField         = 'deleted_at';

	// Validation
	protected $validationRules      = [];
	protected $validationMessages   = [];
	protected $skipValidation       = false;
	protected $cleanValidationRules = true;

	// Callbacks
	protected $allowCallbacks       = true;
	protected $beforeInsert         = [];
	protected $afterInsert          = [];
	protected $beforeUpdate         = [];
	protected $afterUpdate          = [];
	protected $beforeFind           = [];
	protected $afterFind            = [];
	protected $beforeDelete         = [];
	protected $afterDelete          = [];

Create Route

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


$routes->get("browser-usage", "BrowserController::index");


Create Controller

Back to terminal and run this spark command to create application controller.

$ php spark make:controller Browser --suffix

It will create BrowserController.php file at /app/Controllers folder.


namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\BrowserModel;

class BrowserController extends BaseController
	public function index()
		$object = new BrowserModel();

		$browsers = $object->findAll();

		$dataPoints = [];

		foreach ($browsers as $browser) {
			$dataPoints[] = [
				"name" => $browser['name'],
				"y" => floatval($browser['total_usage'])

		return view("pie-chart", [
			"data" => json_encode($dataPoints)

Create View File & Render

Next, create a view file with name pie-chart.php at /app/Views folder. Open pie-chart.php and write this following code into it.

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

    <title>Pie Chart Integration in CodeIgniter 4</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>


    <div class="container">
        <h2 style="text-align: center;">Pie Chart Integration in CodeIgniter 4</h2>
        <div class="panel panel-primary">
            <div class="panel-heading">Pie Chart Integration in CodeIgniter 4</div>
            <div class="panel-body">
                <div id="pie-chart"></div>

    <script src="https://code.highcharts.com/highcharts.js"></script>
    <script src="https://code.highcharts.com/modules/exporting.js"></script>
    <script src="https://code.highcharts.com/modules/export-data.js"></script>
    <script src="https://code.highcharts.com/modules/accessibility.js"></script>
        $(function() {
            Highcharts.chart('pie-chart', {
                chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    plotShadow: false,
                    type: 'pie'
                title: {
                    text: 'Browser Usage World wide'
                tooltip: {
                    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
                accessibility: {
                    point: {
                        valueSuffix: '%'
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: true,
                            format: '<b>{point.name}</b>: {point.percentage:.1f} %'
                series: [{
                    name: 'Browsers',
                    colorByPoint: true,
                    data: <?= $data ?>


Application Testing

Open project terminal and start development server via command:

php spark serve

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

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

Learn about Line Chart Integration in CodeIgniter 4, Click here.

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.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more