Codeigniter 4 Google Bar & Line Charts Example

Codeigniter 4 Google Bar & Line Charts Example. In this tutorial, we will show you how to create a Google Bar & Line Charts in Codeigniter 4 application.

Google Charts is a powerful tool for visualizing data on the web. It is a JavaScript library that provides a wide variety of charts to meet your data visualization needs.

In this tutorial, we will use the Google Charts library to create a Bar & Line Charts in Codeigniter 4 application.

Step 1 – Download & Install Codeigniter 4

Step 2 – Setup Database Credentials

Step 3 – Create Table & Insert Data

Step 4 – Create Routes

Step 5 – Create Controller

Step 6 – Create View File

Step 7 – Run Development Server

Step 1 – Download & Install Codeigniter 4

In this step, you need to download and install the Codeigniter 4 application into your system. So let’s open the command prompt and run the below command to download the Codeigniter 4 fresh setup.

composer create-project codeigniter4/appstarter codeigniter-4

Step 2 – Setup Database Credentials

In this step, you need to open the “.env” file and set up the database credential and move next step :

database.default.hostname = localhost database.default.database = ci4 database.default.username = root database.default.password = root database.default.DBDriver = MySQLi

Step 3 – Create Table & Insert Data

In this step, you need to create a “sales” table and insert some dummy records in the “sales” table. So let’s create a “sales” table and insert some dummy records in the “sales” table.

CREATE TABLE `sales` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `month` varchar(50) NOT NULL, `sales` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `sales` (`id`, `month`, `sales`) VALUES (1, ‘January’, 1000), (2, ‘February’, 2000), (3, ‘March’, 3000), (4, ‘April’, 4000), (5, ‘May’, 5000), (6, ‘June’, 6000), (7, ‘July’, 7000), (8, ‘August’, 8000), (9, ‘September’, 9000), (10, ‘October’, 10000), (11, ‘November’, 11000), (12, ‘December’, 12000);

Step 4 – Create Routes

In this step, you need to create routes for the Google Bar & Line Charts. So let’s add the following routes in the “routes.php” file.

use App\Controllers\Home; $routes->get(‘/’, [Home::class, ‘index’]); $routes->get(‘bar-chart’, [Home::class, ‘barChart’]); $routes->get(‘line-chart’, [Home::class, ‘lineChart’]);

Step 5 – Create Controller

In this step, you need to create a controller file. So let’s create a controller file “Home.php” in this path “app/Controllers/Home.php”.

getSales(); return view(‘bar_chart’, $data); } public function lineChart() { $model = new SalesModel(); $data[‘sales’] = $model->getSales(); return view(‘line_chart’, $data); } }

Step 6 – Create View File

In this step, you need to create two view files “home.php” and “bar_chart.php” and “line_chart.php” in this path “app/Views/”.

Codeigniter 4 Google Bar & Line Charts Example

Codeigniter 4 Google Bar & Line Charts Example

” class=”btn btn-primary”>Line Chart

Codeigniter 4 Google Bar & Line Charts Example

Codeigniter 4 Google Bar Chart Example

Codeigniter 4 Google Bar & Line Charts Example

Codeigniter 4 Google Line Chart Example

Step 7 – Run Development Server

In this step, you need to start the development server. So let’s start the development server using the following command.

php spark serve

Now, you can open the browser and hit the following URL on it.

http://localhost:8080

Conclusion

In this tutorial, you have learned how to create a Google Bar & Line Charts in Codeigniter 4 application.

Recommended CodeIgniter Tutorials

Dynamic line and bar charts in codeigniter 4 using google library; In this tutorial, you will learn how to create bar chart and line chart in codeigniter 4 using Google Chart js library.

By using the following steps, you can create your bar chart and line chart in codeigniter 4 project using google chart js library:

  • Step 1: Setup Codeigniter 4 Project
  • Step 2: Basic Configurations
  • Step 3: Create Table in Database
  • Step 4: Setup Database Credentials
  • Step 5: Create Controller
  • Step 6: Create View
  • Step 7: Create Route
  • Step 8: Start Development Server

Step 1: Setup Codeigniter 4 Project

In this step, you will download the latest version of Codeigniter 4, Go to this link https://codeigniter.com/download Download Codeigniter 4 fresh new setup and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”

Step 2: Basic Configurations

Next, you will set 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 Table in Database

In this step, you need to create table in database and as well as insert some data for google bar and line chart in codeiginter 4. So visit your phpmyadmin panel and execute the following sql query in it:

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]', '9000000001', '2019-01-01'),
  (2, 'Admin', '[email protected]', '9000000002', '2019-02-01'),
  (3, 'User', '[email protected]', '9000000003', '2018-03-01'),
  (4, 'Editor', '[email protected]', '9000000004', '2019-04-01'),
  (5, 'Writer', '[email protected]', '9000000005', '2017-05-01'),
  (6, 'Contact', '[email protected]', '9000000006', '2019-06-01'),
  (7, 'Manager', '[email protected]', '9000000007', '2019-07-01'),
  (8, 'John', '[email protected]', '9000000055', '2016-08-01'),
  (9, 'Merry', '[email protected]', '9000000088', '2019-09-01'),
  (10, 'Keliv', '[email protected]', '9000550088', '2019-10-01'),
  (11, 'Herry', '[email protected]', '9050550088', '2019-11-01'),
  (12, 'Mark', 'm[email protected]', '9050550998', '2019-12-01');

Step 4: Setup Database Credentials

In this step, you need to connect our project to the database. you need to go app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, you need to set up database credentials in this file like below.

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

Step 5: Create Controller

In this step, Visit app/Controllers and create a controller name GoogleCharts.php. In this controller, you need to add the following methods 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);
    }

}

Step 6: Create View

In this step, you need to create one view files name home.php and update the following code into your file:

<!Doctype html>
<html>
<head>
  <title>Google Date Wise Bar and Line Chart Codeigniter 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">
    <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>
</html>

Implement Javascript code

Finally, need to implement javascript code for showing a data on google bar chart. Now we will put the code on script tag after the closing of body tag.

<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>

Step 7: Create Route

In this step, you need to create a route that renders the table into the view, place the following code in app/Config/Routes.php file.

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

Step 8: Start Development Server

In this step, open your terminal and execute the following command to start development sever:

php spark serve

Then, Go to the browser and hit below the URL:

http://localhost:8080

Conclusion

In this codeigniter google bar and line charts tutorial, you have successfully got the record from a database and display it on the google line and bar charts in codeigniter 4 app.

If you have any questions or thoughts to share, use the comment form below to reach us.

Recommended Codeigniter Tutorials

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?