Using Chart Js Implement Pie Chart In Codeigniter

Using Chart Js Implement Pie Chart In Codeigniter

In this codeigniter and chart js tutorial, We would love to share with you how to get last week records from day wise using MySQL codeigniter and also using this record we will draw pie chart with chart js.

In this Codeigniter tutorial, You will learn how to get last week record (day wise) from mysql database of last week and month and how to show the data on pie chart with codeigniter usin chart js.

We will fetch data day/date wise of the last week from mysql database. Every day, Many users registered from our database. We provide demo link at the end of article. Checkout the link.

We will draw pie chart in codeigniter using chart.js . Chart js is used to draw charts, you can use this and draw many types of charts, like pie chart, bar chart, line chart etc.

Codeigniter Pie Chart Using Chart Js

  • Download Codeigniter Latest
  • Basic Configurations
  • Create Database With Table
  • Setup Database Credentials
  • Make New Controller
  • Create Views
  • Start Development server
  • Conclusion

Download Codeigniter Project

In this step we will download the latest version of Codeigniter, Go to this link Download Codeigniter download the fresh setup of codeigniter and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”

Basic Configurations

Next we will set the some basic configuration on config.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

$config['base_url'] = 'http://localhost/demo/';

Create Database With Table

In this step, we need to create database name demo, so let’s open your phpmyadmin and create the database with the name demo . After successfully create a database, you can use the below sql query for creating a table in your database.

    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;

Setup Database Credentials

In this step, We need to connect our project to database. we need to go application/config/ and open database.php file in text editor. After open the file in text editor, We need to setup database credential in this file like below.

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'demo',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE

Create Controller

Now we need to create a controller name Chart.php. In this controller we will create some method/function. We will build some of the methods like :

  • Index() – This is used to fetch the record from database and pass the data to view.

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

class Chart extends CI_Controller {

    public function __construct() {
        // load model
     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);

In this controller function, we fatch the record from mysql database for showing the data on bar charts using chart js with codeigniter.

Create Views

Now we need to create pie_chart.php, go to application/views/ folder and create pie_chart.php file. Here put the below html code for showing data on pie charts.

<!DOCTYPE html>
  <title>ChartJS - Pie</title>
  <!-- Latest CSS -->
 <link rel="stylesheet" href="">
  <div class="chart-container">
    <div class="pie-chart-container">
      <canvas id="pie-chart"></canvas>

  <!-- javascript -->
   <script src=""></script>
   <script src=""></script> 

Implement Javascript code

Finally we will implement javascript code for showing a data on morris stacked and bar charts. Now we will put the code on script tag after the closing of body tag.

      //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",
            backgroundColor: [
            borderColor: [
            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


In this script code, we have intialize the chart pie with php codeigniter and set the data on it using chart js.

Start Development server

For start development server, Go to the browser and hit below the url.



In this chart js and codeigniter tutorial, We have successfully fetch the last week record from database of the current month and implement on the Pie charts using Chart Js.

You may like

  1. Codeigniter 3 Create First Ajax CRUD Application
  2. Codeigniter Send Email With Gmail Smtp Protocol
  3. Laravel Ajax CRUD(DataTables Js) Tutorial Example
  4. Laravel – Ajax CRUD (Operation) Application Example
  5. Laravel Angular JS CRUD Example Tutorial
  6. Upload Files/Images to Amazon s3 Cloud Using Laravel 6 Filesystem
  7. Laravel CKEditor with Image Upload
  8. Laravel Ajax Image Upload Tutorial Example From Scratch

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorTuts Make

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Javascript, JQuery, Laravel, Livewire, Codeigniter, Vue JS, Angular JS, React Js, WordPress, and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *