In this tutorial, we will learn how to implement or create a bar chart in the CodeIgniter application using Chart JS, and fetch month-wise records from MySQL database and display them on a bar chart.
Codeigniter Bar Chart Using Chart Js
Here are steps:
- Download Codeigniter Latest
- Basic Configurations
- Create Table in Database
- Configure Database
- Make New Controller
- Create Views
- Test This Project
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 to “demo”
Basic Configurations
Set base URL in application/config/config.php
file:
$config['base_url'] = 'http://localhost/demo/';
Create Table in DB
Run the following SQL query to create table in 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;
Configure Database
Set up database in application/config/database.php
file:
$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
Create a controller name Chart.php and methods in it in application/controllers
folder to handle bar chart view and data:
<?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 bar_chart() {
$query = $this->db->query("SELECT COUNT(id) as count,MONTHNAME(created_at) as month_name FROM users WHERE YEAR(created_at) = '" . date('Y') . "'
GROUP BY YEAR(created_at),MONTH(created_at)");
$record = $query->result();
$data = [];
foreach($record as $row) {
$data['label'][] = $row->month_name;
$data['data'][] = (int) $row->count;
}
$data['chart_data'] = json_encode($data);
$this->load->view('bar_chart',$data);
}
}
?>
Create Views
Create bar_chart.php in application/views/
folder to show data on bar chart on view:
<!DOCTYPE html>
<html>
<head>
<title>ChartJS - bar</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="bar-chart-container">
<canvas id="bar-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>
Now, initialize bar char on views using chart js:
<script>
$(function(){
//get the bar chart canvas
var cData = JSON.parse(`<?php echo $chart_data; ?>`);
var ctx = $("#bar-chart");
//bar chart data
var data = {
labels: cData.label,
datasets: [
{
label: cData.label,
data: cData.data,
backgroundColor: [
"#DEB887",
"#A9A9A9",
"#DC143C",
"#F4A460",
"#2E8B57",
"#1D7A46",
"#CDA776",
"#CDA776",
"#989898",
"#CB252B",
"#E39371",
],
borderColor: [
"#CDA776",
"#989898",
"#CB252B",
"#E39371",
"#1D7A46",
"#F4A460",
"#CDA776",
"#DEB887",
"#A9A9A9",
"#DC143C",
"#F4A460",
"#2E8B57",
],
borderWidth: [1, 1, 1, 1, 1,1,1,1, 1, 1, 1,1,1]
}
]
};
//options
var options = {
responsive: true,
title: {
display: true,
position: "top",
text: "Monthly Registered Users Count",
fontSize: 18,
fontColor: "#111"
},
legend: {
display: true,
position: "bottom",
labels: {
fontColor: "#333",
fontSize: 16
}
}
};
//create bar Chart class object
var chart1 = new Chart(ctx, {
type: "bar",
data: data,
options: options
});
});
</script>
Test This Project
Go to the browser and hit below the url.
http://localhost/demo/chart/bar_chart
Conclusion
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 bar charts using Chart Js.
Rrecommended Posts
Learn Remove index.php in web url using .htaccess file Codeigniter
If you have any questions or thoughts to share, use the comment form below to reach us.