How To Create Simple Bar Chart In Codeigniter Using AmCharts?


AmCharts using Codeigniter. In this article, we will explain to you how to Create Bar Chart In Codeigniter using AmCharts. today we will get data into MySQL.and create charts, plot a bar graph.

There are many types of charts provide by AmCharts, like a bar chart, area chart, line chart, pie chart, amcharts line chart, etc. but here we use a bar chart. very easy to create amcharts line chart.

We can easily integrate AmCharts Codeigniter. here In this article, we are using AmCharts version 3. so you can see below the following steps.

How To Create Simple  Bar Chart In Codeigniter Using AmCharts?

Create Dynamic Pie Chart In Codeigniter using AmChart

  • Step 1: Create a Database in table
  • Step 2: Connect to Database
  • Step 3: Create Controller
  • Step 4: Create View File
Step 1: Create Database In Table

In this step, we have to create a table in the database, so we will create a database using the below code.

CREATE TABLE `login_history` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `login_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
   PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1;
Step 2: Connect To Database

This step Goes to the config folder and opens the database.php file some changes.

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'database name',
	'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 3: Create Controller

We will create an Amchart.php file in the “application/controller” directory and paste the below code in this controller. here we will fetch the last 10 data from the database count login users. that data will be pass in an Amchart and creating bar graphs with amcharts examples.

application/controller/Amchart.php

<?php
 
defined('BASEPATH') OR exit('No direct script access allowed');
 
class Amchart 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 DATE_FORMAT(login_date, "%Y-%m-%d") AS `date`, COUNT(`login_date`) as count FROM login_history WHERE `login_date` >= NOW() - INTERVAL 10 MONTH GROUP BY MONTH(`login_date`) ORDER BY `login_date` ASC'); 
      $records = $query->result_array();
      $data = [];
      foreach($records as $row) {
		$data[] = ['date' => date('Y-m-t',strtotime($row['date'])), 'count' =>$row['count']];
      }
      $data['chart_data'] = json_encode($data);
      $this->load->view('bar_chart',$data);
    }   
}
?>
Step 4: Create View File

We will create the bar_chart.php file in the “application/views/” directory.

application/views/bar_chart.php
<!DOCTYPE html>
<html>
	<head>
		<title>Create Dynamic Pie Chart In Codeigniter using AmChart - phpcodingstuff.com</title>
		<script src="https://www.amcharts.com/lib/3/amcharts.js"></script>
		<script src="https://www.amcharts.com/lib/3/serial.js"></script>
		<script src="https://www.amcharts.com/lib/3/themes/light.js"></script>
		<script src="https://www.amcharts.com/lib/3/plugins/export/export.min.js"></script>
		<link rel="stylesheet" href="https://www.amcharts.com/lib/3/plugins/export/export.css" type="text/css" media="all" />
	</head>
	<body>
		<div id="chartdiv" style="width: 900px; height: 800px;"></div>
		<script>
		var chartData = JSON.parse(`<?php echo $chart_data; ?>`);
            try {
				  var chart = AmCharts.makeChart( "chartdiv", {
				  "type": "serial",
				  "theme":"light",
				  "dataProvider": chartData,
				  "valueAxes": [ {
					"gridColor": "#FFFFFF",
					"gridAlpha": 0.2,
					"dashLength": 0
				  } ],
				  "gridAboveGraphs": true,
				  "startDuration": 1,
				  "graphs": [ {
					"balloonText": "[[category]]: <b>[[value]]</b>",
					"fillAlphas": 0.8,
					"lineAlpha": 0.2,
					"type": "column",
					"valueField": "count"
				  } ],
				  "chartScrollbar": {
					"graph": "g1",
					"scrollbarHeight": 60,
					"backgroundAlpha": 0,
					"selectedBackgroundAlpha": 0.1,
					"selectedBackgroundColor": "#888888",
					"graphFillAlpha": 0,
					"graphLineAlpha": 0.5,
					"selectedGraphFillAlpha": 0,
					"selectedGraphLineAlpha": 1,
					"autoGridCount": true,
					"color": "#AAAAAA",
					"oppositeAxis": false
                    },
				  "chartCursor": {
					"categoryBalloonEnabled": false,
					"cursorAlpha": 0,
					"zoomable": false
				  },
				  "categoryField": "date",
				  "categoryAxis": {
					"gridPosition": "start",
					"gridAlpha": 0,
					"tickPosition": "start",
					"tickLength": 20
				  },
				  "export": {
					"enabled": true
				  }
				} );           
            }
            catch( e ) {
              console.log( e );
            }
		</script>		
	</body>
</html>
How To Create Simple  Bar Chart In Codeigniter Using AmCharts?

I hope it can help you...

Leave a Reply

Your privacy will not be published. Required fields are marked *

We'll share your Website Only Trusted.!!

close