Codeigniter 4 Google Line & Bar Charts Tutorial

Codeigniter 4 line and bar chart example; In this tutorial, i will show you how to implement google line and bar chart in Codeigniter 4 app using google charts library. And as well as learn how to get current month records day wise from mysql db in codeigniter 4 app and using this record; i will implement google bar & line charts.

Create dynamic line and bar chart in Codeigniter 4 example; For Google line and bar chart I will get current year and month wise data day wise from mysql database and implement google bar and line chart and display data from database in codeigniter 4 apps.

Create Google line And Bar Chart In Codeigniter 4

  • Install Codeigniter 4 Application
  • Basic App Configurations
  • Create Database and Table
  • Setup Database Credentials
  • Create Controller Class
  • Create Views
  • Setup Routes
  • Start Development server

Step 1 – Install Codeigniter 4 Application

First of all, you need to ownload the latest version of Codeigniter 4. So, visit this link https://codeigniter.com/download Download Codeigniter 4 app and unzip the setup in your local system xampp/htdocs/ .

Note that, please change the download folder name “demo”.

Step 2 – Basic App Configurations

Now, you need to some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';

Step 3 – Create Database and Table

Create database and table; so open your phpmyadmin and execute the following sql query on it to create table:

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 COMMENT='datatable demo table' AUTO_INCREMENT=1;

  INSERT INTO users (id, name, email, contact_no, created_at) VALUES
  (1, 'Team', '[email protected]', '9000000007', '2021-01-07'),
  (2, 'Admin', '[email protected]', '9000000002', '2021-02-07'),
  (3, 'User', '[email protected]', '9000000003', '2020-03-07'),
  (4, 'Editor', '[email protected]', '9000000004', '2021-04-07'),
  (5, 'Writer', '[email protected]', '9000000005', '2020-05-07'),
  (6, 'Contact', '[email protected]', '9000000006', '2021-06-07'),
  (7, 'Manager', '[email protected]', '9000000007', '2021-07-07'),
  (8, 'John', '[email protected]', '9000000055', '2020-08-07'),
  (9, 'Merry', '[email protected]', '9000000088', '2021-09-07'),
  (10, 'Keliv', '[email protected]', '9000550088', '2021-10-07'),
  (11, 'Herry', '[email protected]', '9050550088', '2021-11-07'),
  (12, 'Mark', '[email protected]', '9050550998', '2021-12-07');

Step 4 – Setup Database Credentials

To connect your codeigniter 4 app to the database. So, visit app/Config/ directory and open Database.php. Then add the databasae details like below into database.php file:

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'test',
        'password' => '4Mu99BhzK8dr4vF1',
        'database' => 'demo',
        '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 5 – Create Controller Class

Create GoogleCharts.php file. So, visit app/Controllers directory and create GoogleCharts.php.Then add the following code into it:

<?php namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;


class GoogleCharts extends Controller
{

    public function index() {

        $db      = \Config\Database::connect();
        $builder = $db->table('users');   

        $query = $builder->query("SELECT COUNT(id) as count,DAY(created_at) as day_date FROM users WHERE MONTH(created_at) = '" . date('m') . "'
        AND YEAR(created_at) = '" . date('Y') . "'
      GROUP BY DAY(created_at)");

      $data['day_wise'] = $query->getResult();
        
	    return view('home',$data);
    }

}
  • The index() function renders bar chart template into the view.

Step 6 – Create Views

Create home.php view file, so visit app/views/ directory and create home.php file. Then add the following HTML into home.php file:

<!Doctype html>
<html>
<head>
  <title>Google Date Wise Bar and Line Chart Codeigniter Tutorial - laratutorials.com</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">
    <div id="line_date_wise" style="width: 900px; height: 500px; margin: 0 auto"></div>
    <div id="bar_date_wise" style="width: 900px; height: 500px; margin: 0 auto"></div>
  </div>  
</div>
</body>

<script language="JavaScript">
  // Draw the pie chart for registered users month wise
  google.charts.setOnLoadCallback(lineChart);

  // Draw the pie chart for registered users year wise
  google.charts.setOnLoadCallback(barChart);
  
  //for
  function lineChart() {

        /* Define the chart to be drawn.*/
        var data = google.visualization.arrayToDataTable([
            ['Date', 'Users Count'],
            <?php 
             foreach ($day_wise as $row){
             echo "['".$row->day_date."',".$row->count."],";
             }
             ?>
        ]);

        var options = {
          title: 'Day 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);
  }
  // for
  function barChart() {

    /* Define the chart to be drawn.*/
    var data = google.visualization.arrayToDataTable([
        ['Date', 'Users Count'],
        <?php 
         foreach ($day_wise as $row){
         echo "['".$row->day_date."',".$row->count."],";
         }
         ?>
    ]);
    var options = {
        title: 'Date wise Registered Users Bar Chart',
        is3D: true,
    };
    /* Instantiate and draw the chart.*/
    var chart = new google.visualization.BarChart(document.getElementById('bar_date_wise'));
    chart.draw(data, options);
  }
</script>
</html>

Step 7 – Setup Routes

To define a route, So, visit app/Config/ directory and open Routes.php file. Then add the following routes into it:

// 
$routes->setDefaultController('GoogleCharts');
$routes->get('/', 'GoogleCharts::index');

Step 8 – Start Development server

Execute the following command into command prompt or terminal to start the codeigniter 4 application:

php spark serve

Then visit your web browser and hit the following url on it:

http://localhost/demo/

OR

http://localhost:8080/

Conclusion

Codeigniter 4 line and bar chart example; In this tutorial,You have learned how to implement google line and bar chart in Codeigniter 4 app using google charts library.

Recommended CodeIgniter 4 Tutorial

  1. How to Install / Download Codeigniter 4 By Manual, Composer, Git
  2. How to Remove Public and Index.php From URL in Codeigniter 4
  3. Codeigniter 4 Form Validation Example Tutorial
  4. How to add jQuery Validation on Form in Codeigniter 4 Example
  5. Codeigniter 4 Ajax Form Submit Validation Example
  6. Codeigniter 4 File Upload Validation Example
  7. Image Upload with Validation in Codeigniter 4
  8. Codeigniter 4 Image Upload Preview Using jQuery Example
  9. Codeigniter 4 Ajax Image Upload Preview Example
  10. How to Upload Multiple Images in Codeigniter 4
  11. Codeigniter 4 Multiple Image Upload with Preview
  12. Codeigniter 4 Pagination Example; Create Pagination in Codeigniter
  13. Simple Codeigniter 4 CRUD with Bootstrap and MySQL Example
  14. Codeigniter 4 CRUD with Datatables Example
  15. Codeigniter 4 Image Crop and Save using Croppie Example
  16. Codeigniter 4 Dependent Dropdown using jQuery Ajax Example
  17. CodeIgniter 4 Rest Api CRUD Example
  18. Codeigniter 4 Login Registration and Logout Example
  19. Codeigniter 4 – Get Address from Latitude and Longitude Ex
  20. Codeigniter 4 Google Column Charts Example

Leave a Comment