Skip to content

All topics  /  CodeIgniter

Codeigniter 4 Google Column Charts Integration Tutorial Example

CodeIgniter ·

Teams applying “Codeigniter 4 Google Column Charts Integration Tutorial Example” in a production project can use the relevant Monitask guide to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.

Before copying the example into a live application, confirm version-specific behaviour with CodeIgniter and test it against the project’s actual database and runtime.

Hi guys,

Today i will explained How to Integration Google Column Charts in Codeigniter 4. This example is so easy to use in Codeigniter 4.

Today i will implemented to the Google Column Charts Integration in Codeigniter 4. I am implemented to the seven steps to implement Google Column Charts in Codeigniter.

We will show you how to get the product’s sales price day wise and represent the sales on the Google column chart after retrieving the data from the database.

So let's start to the example.

Step 1: Create Latest Codeigniter App


Codeigniter Project Project install in a two ways.

<?php
https://codeigniter.com/download
or
composer create-project codeigniter4/appstarter project_name
?>

Step 2: Add Database Credentials

Open the app/Config/Database.php, and insert database name, username and password into the file.

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,
    ];

Step 3: Create Table and Insert Records

Then next step to create table and insert to the few records.

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

Step 4: Formulate Controller

You have to generate a new controller template, right after that add the following code into the 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->orderBy("s ASC, day ASC");
        $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);               
    }
}

Step 5: Setting Up Route next to make the route for showing charts, you need to go to app/Config/Routes.php and define the given below routes in the file

$routes->setDefaultController('GColumnChartController');
$routes->get('/google-column-chart', 'GColumnChartController::initChart');

Step 6: Create Column Chart View File

Then Next, you need to create the view file, where you will constitute the chart using the google chart js, bootstrap and most importantly the data coming from the database.

Add code into 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 Column Chart in Codeigniter Nicesnippets.com</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
</head>
    <body>
        <div class="container">
            <div id="GoogleColumnChart" style="height: 500px; width: 100%"></div>
        </div>
        <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
        <script>
            google.charts.load('visualization', "1", {
                packages: ['corechart']
            });
            function showChart() {
                var data = google.visualization.arrayToDataTable([
                    ['Day', 'Products Count'], 
                    <?php 
                        foreach($products as $row) {
                            echo "['".$row['day']."',".$row['sell']."],";
                        } 
                    ?>
                ]);
                var options = {
                    title: 'Last week sales',
                    isStacked: true
                };
                var chart = new google.visualization.ColumnChart(document.getElementById('GoogleColumnChart'));
                chart.draw(data, options);
            }
            google.charts.setOnLoadCallback(showChart);
        </script>
    </body>
</html>

Step 7: Run Codeigniter Application

In this last step, you have to open the terminal, type command to run the application.

php spark serve

Then next run the url in your browser.

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

Output

Now you can check your own.