PHP CodeIgniter 4 Google Bar & Line Charts Tutorial

Last Updated on by in CodeIgniter

PHP Codeigniter 4 google line and bar charts tutorial; If you are a beginner and trouble dealing with integrating Google Charts in Codeigniter 4, we can promise you that this comprehensive guide is for you.

In this extensive tutorial, we will teach you how to get data from the MySQL database, implement it in the Google line chart in Codeigniter, and add identical data in the Codeigniter bar chart.

Codeigniter Google Line Chart Example

Before we move further, let’s quickly understand what a line chart is.

A line graph is also known as a line chart, primarily a curve chart shows data intuitively as a series of data points called ‘markers’ joined by straight-line portions.

We will describe how to add a google line chart in the Codeigniter app. We will not create a static chart but fetch the MySQL data and pair it with the line chart.

Codeigniter Google Bar (Column) Chart Example

A bar chart can be defined vertically or horizontally; it helps to show categorical data with square bars with heights or lengths comparable to the values they represent.

PHP Codeigniter 4 Google Bar & Line Charts Integration Example

  • Step 1: Install New Codeigniter App
  • Step 2: Make Database Connection
  • Step 3: Create Table & Insert Data SQL
  • Step 4: Formulate New Route
  • Step 5: Create Chart Controller
  • Step 6: Add Line Chart in View
  • Step 7: Start CI Project

Install New Codeigniter App

You can either execute the following command to dynamically download the codeigniter app, make sure to install Composer tool before that.

composer create-project codeigniter4/appstarter

But if you don’t want to rely on command-line tool, then click on the given link to manually download codeigniter the app.

https://codeigniter.com/download

Don’t forget to update the default project folder name to “my_ci_app” or anything fancy you want.

Make Database Connection

To make the database connection, open the app/Config/Database.php, inside the default array enter your database name, username and password.

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'codeigniter_db',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
    ];

Create Table & Insert Data SQL

The database connection has been made, app and DB are now be able to communicate.

Let’s create the table and insert a couple of records into it for the Google bar and line chart in Codeigniter.

CREATE TABLE `product` (
  `id` int(11) NOT NULL COMMENT 'Primary Key',
  `name` varchar(255) NOT NULL COMMENT 'name',
  `sell` varchar(55) NOT NULL COMMENT 'sell',    
  `created_at` varchar(30) NOT NULL COMMENT 'created at'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Atomic database';


INSERT INTO `product` (`id`, `name`, `sell`, `created_at`) VALUES
(1, 'Coca Cola', '5000', '2021-05-01'),
(2, 'Pepsi', '7000', '2021-05-02'),
(3, 'Coke Zero', '19000', '2021-05-03'),
(4, 'Pepsi Max', '1500', '2021-05-04'),
(5, 'Diet Coke', '19000', '2021-05-05'),
(6, 'Pepsi Light', '3000', '2021-05-06'),
(7, 'Gatorade', '22000', '2021-05-07');

Formulate New Route

In this step, you require to open the app/Config/Routes.php, incorporate the controller in the route method and set up the new route.

/*
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
*/


$routes->setDefaultController('GColumnChartController');
$routes->match(['get', 'post'], 'GColumnChartController/initChart', 'GColumnChartController::initChart');

Create Chart Controller

Get into the controllers’ folder, set up a new controller file here, apparently define the single function inside the controller class.

This function will simultaneously fetch and filter the records from the database using the Codeigniter 4 SQL queries and pass the retrieved data into the view file.

Add code in app/Controllers/GColumnChartController.php file.

<?php 

namespace App\Controllers;
use CodeIgniter\Controller;


class GColumnChartController extends Controller
{

    public function index() {
        return view('chart');
    }
    
    public function initChart() {
        
        $db = \Config\Database::connect();
        $builder = $db->table('product');

        $query = $builder->select("COUNT(id) as count, sell as s, DAYNAME(created_at) as day");
        $query = $builder->where("DAY(created_at) GROUP BY DAYNAME(created_at), s")->get();
        $record = $query->getResult();

        $products = [];

        foreach($record as $row) {
            $products[] = array(
                'day'   => $row->day,
                'sell' => floatval($row->s)
            );
        }
        
        $data['products'] = ($products);    
        return view('chart', $data);                
    }
 
}

Add Google Line Chart in View

This section will demonstrate how to add google bar and line charts in Codeigniter’s view file.

Make sure to create the chart.php inside the controller folder and inject the complete code in the file.

This file holds the Google charts js and the JavaScript functions and methods to display the line and bar chart in the Codeigniter app.

Now, add below code in app/Views/chart.php file.

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Google Bar & Column Charts in Codeigniter</title>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>

<body>

	<body>
		<div class="container">
			<div class="mb-5 mt-5">
				<div id="GoogleLineChart" style="height: 400px; width: 100%"></div>
			</div>

			<div class="mb-5">
				<div id="GoogleBarChart" style="height: 400px; width: 100%"></div>
			</div>
		</div>


		<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
		<script>
			google.charts.load('current', {'packages':['corechart', 'bar']});
			google.charts.setOnLoadCallback(drawLineChart);
			google.charts.setOnLoadCallback(drawBarChart);

            // Line Chart
			function drawLineChart() {
				var data = google.visualization.arrayToDataTable([
					['Day', 'Products Count'],
						<?php 
							foreach ($products as $row){
							   echo "['".$row['day']."',".$row['sell']."],";
						} ?>
				]);

				var options = {
					title: 'Line chart product sell wise',
					curveType: 'function',
					legend: {
						position: 'top'
					}
				};
				var chart = new google.visualization.LineChart(document.getElementById('GoogleLineChart'));
				chart.draw(data, options);
			}
			
			
			// Bar Chart
			google.charts.setOnLoadCallback(showBarChart);
			function drawBarChart() {
				var data = google.visualization.arrayToDataTable([
					['Day', 'Products Count'], 
						<?php 
							foreach ($products as $row){
							   echo "['".$row['day']."',".$row['sell']."],";
							}
						?>
				]);
				var options = {
					title: ' Bar chart products sell wise',
					is3D: true,
				};
				var chart = new google.visualization.BarChart(document.getElementById('GoogleBarChart'));
				chart.draw(data, options);
			}
			
		</script>

	</body>

</html>

Start CI Project

You have come closer to check the app on the browser; without wasting time, type the following command in the console and hit enter.

php spark serve

After the development server starts, use the below url to test the bar chart in Codeigniter.

http://localhost:8080/show-google-charts

PHP Codeigniter 4 Google Bar & Line Charts Tutorial

Conclusion

Google Charts are dynamic, interactive, which amplify the data visualization experience for your users. It comes with tons of features that might help in customizing the charts.

In this quick tutorial, we thoroughly understand how to integrate Google line charts and bar or column charts in Codeigniter.

We believe this guide will help you.