CodeIgniter 4 Google Bar & Line Charts Example

CodeIgniter 4 Google Bar & Line Charts Example

Hello friends, Today we will show CodeIgniter 4 Google Bar & Line Charts Example. In this example we will show how to integrate google bar & line charts in Codeigniter 4. Here you can easily integrate Google bar and line Chart day, week, and month-wise in CodeIgniter 4.

Here we will show CodeIgniter 4 Google Bar Charts and Line Charts. we will teach you how to get data from the MySQL database, implement it in the Google line chart in Codeigniter 4, and add identical data in the Codeigniter 4 bar chart.

CodeIgniter 4 Google Bar and Line Charts

Step 1: Install CodeIgniter App

CodeIgniter Project Project install in a two ways.

https://codeigniter.com/download
or
composer create-project codeigniter4/appstarter project_name

Step 2: Make Database Connection

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 & Insert Data SQL

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: Create Chart Controller

You have to generate a new controller template, right after that add the bellow 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->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: Formulate New Route

In this step you make the route for showing charts, you required to go to app/Config/Routes.php and define the given following routes in the file

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

Step 6: Add Line Chart in View

Then next, you required 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.

Read Also :  Codeigniter 4 Ajax Image Upload With Preview Example

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 Bar & Column Charts in Codeigniter Nicesnippets.com</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
    <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>

Step 7: Start CodeIgniter Project

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

I hope you understand of CodeIgniter 4 Google Bar and Line Charts Tutorial and it can help you…

Read Also :  Get all Data from Database in CodeIgniter