Skip to content

All topics  /  CodeIgniter

Codeigniter 4 Pie Chart Using Chart Js Example Tutorial

CodeIgniter ·

Teams applying “Codeigniter 4 Pie Chart Using Chart Js Example Tutorial” in a production project can use the official resource to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.

Before copying the example into a live application, confirm version-specific behaviour with CodeIgniter and test it against the project’s actual database and runtime.

Hi Dev,

I will explain step by step tutorial codeigniter 4 pie chart using chart js. This article goes in detailed on using chart js implement pie chart in codeigniter 4. you'll learn codeigniter 4 pie chart integration using chart js example. if you want to see example of pie chart responsive then you are a right place. you will do the following things for codeigniter 4 pie chart integration.

I’m going to show you about this article goes in detailed on using chart js implement pie chart in codeigniter 4..

So, let's started the example...

Step 1: Install Codeigniter 4


This is optional; however, if you have not created the codeigniter app, then you may go ahead and execute the below command:

composer create-project codeigniter4/appstarter ci-news

Step 2: Create Database With Table

After successfully install the composer open your terminal fire this following command.

you need to create database and table.

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 COMMENT='datatable demo table' AUTO_INCREMENT=1;

Step 3: Setup Database Credentials

In this section we require to connect our project to the database. we need to go app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, We need to set up database credentials in this file like below.

app/Config/Database.php

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

Step 4: Create Controller

Here, in this fourth step go to app/Controllers and create a controller name Chart.php. In this controller, we will create some method/function.

app/Controllers/Chart.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

 
class Chart extends CI_Controller {

    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function __construct() {
        parent::__construct();
        $this->load->database();
        $this->load->helper(array('url','html','form'));
    }       
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function pie_chart_js() {

   
        $query =  $this->db->query("SELECT created_at as y_date, DAYNAME(created_at) as day_name, COUNT(id) as count  FROM users WHERE date(created_at) > (DATE(NOW()) - INTERVAL 7 DAY) AND MONTH(created_at) = '" . date('m') . "' AND YEAR(created_at) = '" . date('Y') . "' GROUP BY DAYNAME(created_at) ORDER BY (y_date) ASC"); 

 
        $record = $query->result();
        $data = [];

 
        foreach($record as $row) {
            $data['label'][] = $row->day_name;
            $data['data'][] = (int) $row->count;
        }
        $data['chart_data'] = json_encode($data);
        $this->load->view('pie_chart',$data);
    }
}
?>

Step 5: Create Views

We need to create one view files name pie_chart.php and update the following code into your file:

<!DOCTYPE html>
<html>
<head>
  <title>ChartJS - Pie</title>
  <!-- Latest CSS -->
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
  <div class="chart-container">
    <div class="pie-chart-container">
      <canvas id="pie-chart"></canvas>
    </div>
  </div>

 
  <!-- javascript -->
   <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js"></script>
   <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
</body>
</html>

Here, now we are require to create a javascript file for showing a data on morris stacked and bar charts you can following this below code.

<script>
$(function(){

      
      /*------------------------------------------
      --------------------------------------------
      Get the Pie Chart Canvas 
      --------------------------------------------
      --------------------------------------------*/
      var cData = JSON.parse(`<?php echo $chart_data; ?>`);
      var ctx = $("#pie-chart");

 
      /*------------------------------------------
      --------------------------------------------
      Pie Chart Data 
      --------------------------------------------
      --------------------------------------------*/
      var data = {
        labels: cData.label,
        datasets: [
            {
                label: "Users Count",
                data: cData.data,
                backgroundColor: [
                    "#DEB887",
                    "#A9A9A9",
                    "#DC143C",
                    "#F4A460",
                    "#2E8B57",
                    "#1D7A46",
                    "#CDA776",
                ],
                borderColor: [
                    "#CDA776",
                    "#989898",
                    "#CB252B",
                    "#E39371",
                    "#1D7A46",
                    "#F4A460",
                    "#CDA776",
                ],
                borderWidth: [1, 1, 1, 1, 1,1,1]
            }
        ]
    };

 
    var options = {
        responsive: true,
        title: {
            display: true,
            position: "top",
            text: "Last Week Registered Users -  Day Wise Count",
            fontSize: 18,
            fontColor: "#111"
        },
        legend: {
            display: true,
            position: "bottom",
            labels: {
                fontColor: "#333",
                fontSize: 16
            }
        }
    };

 
    /*------------------------------------------
    --------------------------------------------
    create Pie Chart class object
    --------------------------------------------
    --------------------------------------------*/
    var chart1 = new Chart(ctx, {
        type: "pie",
        data: data,
        options: options
    });

 
});
</script>

Step 6: Run Codeigniter App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Codeigniter app:

php spark serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8080/