Dynamic Pie Chart in Codeigniter

In this tutorial, we would love to share with you how to create pie charts using ChartJS in CodeIgniter projects.

Here are steps to create pie chart using chart Js:

1. Download Codeigniter Project

In this step, we will download the latest version of CodeIgniter, go to this link Download CodeIgniter Download the new setup of CodeIgniter and unzip the setup in your local system xampp/htdocs/.

2. Add Configurations

Edit application/config/config.php file and add base URL in it:

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

3. Create a Table in DB

Run the following query to create table in your 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;

4. Add Database

Edit application/config/database.php, file and add the database username, password, and database name in it:

$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
);

5. Create Controller

Create Chart.php in the application/controller folder, and then create some methods in it to dynamically handle the pie chart data in the 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);
}

}
?>

6. Create Views

Create pie_chart.php view file in application/views/ folder to show pie chart in it:

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

Add the ChartJS library and its function to handle pie chart creation:

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

7. Test This Project

Go to the browser and hit below the url.

http://localhost/demo/chart/pie_chart_js

Conclusion

In this tutorial, we have successfully fetched the previous week’s record from the current month database and applied to pie chart 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 Image Upload Tutorial Example From Scratch

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

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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