Using Chart Js Implement Pie Chart In Codeigniter

Using Chart Js – Welcome to this tutorial on using Codeigniter and Chart.js! We’ll show you how to get last week’s records day by day using MySQL in Codeigniter. We’ll also use these records to create a pie chart with Chart.js.

In this tutorial, you’ll learn how to retrieve the day-by-day records of the last week and month from a MySQL database using Codeigniter. We’ll be fetching data from the database of users who registered every day. At the end of this article, we’ll provide a demo link for you to check out.

To draw our pie chart, we’ll be using Chart.js. This is a powerful library that can be used to create many different types of charts, such as pie charts, bar charts, and line charts.

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 next step, we’re going to download the newest version of Codeigniter. To do this, go to the website Download Codeigniter and get the most up-to-date setup. After you’ve downloaded it, unzip the setup in your local system’s xampp/htdocs/ folder. You can also rename your project folder to whatever you’d like.

Basic Configurations

Now it’s time to do some basic configuration settings on the config.php file. To do this, we’ll navigate to the application/config/config.php file and open it up in a text editor.

set base url like this:-

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

Create Database With Table

For this next step, we’ll need to create a database with the name “demo” To do this, we’ll open up PHPMyAdmin and create the database with that name. Once it’s successfully created, we can use the following SQL query to create a table in the database.

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;

Setup Database Credentials

In the following step, we’ll connect our CRUD app project to the database. To do this, we’ll go to the

application/config/database.php

file and set up our database credentials. In this file, we’ll add our database name, username, and password.

$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.
<?php
 
defined('BASEPATH') OR exit('No direct script access allowed');
 
class Chart extends CI_Controller {
 
    public function __construct() {
        parent::__construct();
        // load model
        $this->load->database();
        $this->load->helper(array('url','html','form'));
    }       
     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);
    }
     
}
?>

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 it’s time to create the “pie_chart.php” file. To do this, navigate to the “application/views/” folder and create a new file named “pie_chart.php”. In this file, copy and paste the following HTML code to display your data on a pie chart.

<!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>

Implement JavaScript Code

Lastly, we’ll implement the JavaScript code to display our data on Morris stacked and bar charts. To do this, place the code within a script tag after the closing body tag of your HTML file.

<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],
                },
            ],
        };

        //options
        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>

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.

http://localhost/demo/chart/pie_chart_js

Congratulations! You have successfully fetched last week’s records from your database of the current month and implemented them on your pie chart using Chart.js in this Codeigniter tutorial.

You May Like

Codeigniter Autocomplete Search From Database – jQuery UI

First Codeigniter 3 CRUD (Create,Read,Update,Delete) via Mysql

Codeigniter PHP Google Recaptcha Form Validation Example

Update Query in Codeigniter Using Where Condition

Leave a Reply

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