Codeigniter 4 Google Line Chart Integration Tutorial

Share this Article
Reading Time: 6 minutes
1,331 Views

Inside this article, we will see the concept of CodeIgniter 4 Google Line Chart Integration. This article will be step by step graph integration.

Line chart represents the information in very graphical view which provides the complete idea about data. Google charts provides several graphical view. Here, we will use google charts to add Line chart into CodeIgniter 4 application.

Learn More –

Let’s get started.


CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


.env Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file.

Now we are ready to use environment variables.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.


Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.


Create Database Table

Next, we need a table. That table will be responsible to store data.

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;

Successfully, we have created a table.


Database Connection

Open .env file from project root.

Search for DATABASE. You should see the connection environment variables. Give your updated details of database connection string.

 
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = localhost
database.default.database = codeigniter4_app
database.default.username = root
database.default.password = root
database.default.DBDriver = MySQLi
database.default.DBPrefix =
   

Now, database successfully connected with the application.


Import Test Data to Table

Here, we have a simple script to insert some test values into table. Copy code and execute inside created database.

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `name`, `email`, `contact_no`, `created_at`) VALUES
(1, 'Sanjay Kumar', 'sanjay@test.com', '8527419635', '2019-01-01'),
(2, 'Vijay Rohila', 'vijay@net.com', '8529632145', '2019-02-01'),
(3, 'Ashish Kumar', 'ashish@gmail.com', '8956237415', '2018-03-01'),
(4, 'Dhananjay Negi', 'dj@test.com', '9000000004', '2019-04-01'),
(5, 'Pradeep Goyal', 'pradeep@test.com', '8794563215', '2017-05-01'),
(6, 'Monu Thakur', 'monu_thakur@test.com', '8749653215', '2019-06-01'),
(7, 'Prateek', 'prateek@test.com', '7412589632', '2019-07-01'),
(8, 'Raj Kishore', 'raj_kishore@test.com', '9874563215', '2016-08-01'),
(9, 'Deepak Kumar', 'deepak@test.com', '7458963214', '2019-09-01'),
(10, 'Rajan', 'rajan@test.com', '9874563218', '2019-10-01'),
(11, 'Herry', 'herry@test.com', '8526397418', '2019-11-01'),
(12, 'Mark', 'mark@test.com', '9852631478', '2019-12-01');

When you will execute this Sql query into your PhpMyadmin, it will insert dummy rows into users table.


Create Controller

Open project into terminal and run this spark command to create controller.

$ php spark make:controller Chart --suffix

It will create ChartController.php file inside /app/Controllers folder. Open controller file and write this complete code into it.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class ChartController extends BaseController
{
	private $db;

	public function __construct()
	{
		$this->db = \Config\Database::connect();
	}

	public function index()
	{
		$year_wise = $this->db->query("SELECT COUNT(id) as count,YEAR(created_at) as year FROM users GROUP BY YEAR(created_at)")->getResult();

		$data['year_wise'] = $year_wise;

		return view("line-chart", $data);
	}
}

Create Route

Open Routes.php from /app/Config folder. Add this route into it.

//...

$routes->get('line-chart', 'ChartController::index');

//...

Create View File

Next, create a view file with name line-chart.php inside /app/Views folder.

Open line-chart.php and write this following code into it.

<!Doctype html>
<html>
<head>
  <title>CodeIgniter 4 Google Line Chart Integration Tutorial</title>
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> 
  <script type="text/javascript">
      google.charts.load('visualization', "1", {
          packages: ['corechart']
      });
  </script>
</head>
<body>
<div class="row">
  <div class="col-md-12">
    <h2 style="text-align:center;">CodeIgniter 4 Google Line Chart Integration Tutorial</h2>
    <div id="line_date_wise" style="width: 900px; height: 500px; margin: 0 auto"></div>
  </div>  
</div>
<script>
 
  // Draw the line chart for registered users year wise
  google.charts.setOnLoadCallback(lineChart);
   
  // for
  function lineChart() {
 
 /* Define the chart to be drawn.*/
 var data = google.visualization.arrayToDataTable([
     ['Year', 'Users Count'],
     <?php 
      foreach ($year_wise as $row){
      echo "['".$row->year."',".$row->count."],";
      }
      ?>
 ]);

 var options = {
   title: 'Year Wise Registered Users Of Line Chart',
   curveType: 'function',
   legend: { position: 'bottom' }
 };
 /* Instantiate and draw the chart.*/
 var chart = new google.visualization.LineChart(document.getElementById('line_date_wise'));
 chart.draw(data, options);
}

</script>
</body>
</html>

Application Testing

Start development server:

$ php spark serve

URL: http://localhost:8080/line-chart

We hope this article helped you to learn Codeigniter 4 Google Line Chart Integration Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5