Codeigniter Create Bar Chart In PHP With Chart Js

PHP , Codeigniter

Nicesnippets

496

11-08-2020


Hi Guys,

In this blog, I will explain you how to create codeigniter create bar chart in php with chart js. i will show bar chart in php with chart js using codeigniter. We will learn how to implement or draw bar in codeigniter application using chart js. How to fetch monthly wise records from MySQL database & using this record how to draw bar chart with chart js with php codeigniter.

We will fetch data monthly wise of the current year from php mysql database. Using this data we will draw the bar chart with chart js and php codeigniter.

We will also learn about some global configuration options that can be used to change the fonts and tooltips of different charts. In this tutorial, we will learn how to create bar charts in Chart.js with php mysql Codeigniter.

In PHP codeigniter or other framework Using chart js, we can draw many types of charts, like bar chart, area chart, line chart, pie chart etc.

Step 1: Download Codeigniter Project

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

Step 2: Basic Configurations

Next, we will set some basic configuration on the app/config/app.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/';

Step 3: Create Database With Table

In this step, we need to create a 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.

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 4: Setup Database Credentials

In this step, we need 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.

$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

);

Step 5: 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() {

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

}

}

?>

In this controller function, we fatch the record from database for showing the data on bar chart.

Step 6: Create Views

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

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

Step 7:Implement Javascript code

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

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

In this script code, we have intialize the chart bar 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/bar_chart

It will help you...