Codeigniter 4 Google Bar/Column Charts Tutorial Example

Codeigniter 4 Google Bar/Column Charts Tutorial Example with Demo. In this tutorial, we will show you how to create a Google Bar/Column Chart using Codeigniter 4.

Google Charts is a powerful tool for creating interactive charts and graphs. It is a JavaScript library that provides a wide variety of charts and graphs for data visualization.

In this tutorial, we will use Codeigniter 4 to create a Google Bar/Column Chart. We will use the Google Charts library to create the chart.

We will create a simple page that displays a Bar/Column Chart. We will use the Codeigniter 4 database library to fetch data from the database and display it in the chart.

Step 1: Download & Install Codeigniter 4

First of all, we need to download and install Codeigniter 4 application. So, let’s open the terminal and go to the xampp htdocs folder directory using the command prompt.

cd xampp/htdocs

After that, download the latest version of the Codeigniter 4, using the following command.

composer create-project codeigniter4/appstarter codeigniter-4

Step 2: Setup Database

In this step, we will create a database and table. So, open the phpMyAdmin and create a database as following:

Database Name: codeigniter_4

After that, click on the SQL tab and paste the below SQL query to create a table.

CREATE TABLE `products` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `name` varchar(255) NOT NULL, `price` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step 3: Setup Config

In this step, we will setup the database configuration. So, open the app/Config/Database.php file and configure the database details.

public $default = [ ‘DSN’ => ”, ‘hostname’ => ‘localhost’, ‘username’ => ‘root’, ‘password’ => ”, ‘database’ => ‘codeigniter_4’, ‘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 4: Create Controller

In this step, we will create a controller file. So, create a controller file Chart.php in the app/Controllers folder.

findAll(); $data[‘title’] = ‘Google Bar/Column Chart’; echo view(‘chart’, $data); } }

Step 5: Create Model

In this step, we will create a model file. So, create a model file ProductsModel.php in the app/Models folder.

<?php echo $title; ?>

Step 7: Run Development Server

In this step, we will start the development server. So, open the terminal and run the following command.

php spark serve

Now, open the browser and hit the following URL.

http://localhost:8080/chart

Conclusion

In this tutorial, we have learned how to create a Google Bar/Column Chart using Codeigniter 4. We have used the Codeigniter 4 database library to fetch data from the database and display it in the chart.
[ad_1]

Codeigniter 4 google column chart; In this tutorial guide, you will learn how to create Google column or bar charts in Codeigniter with MySQL and fetch month-wise data from MySQL for showing on Google column or bar charts.

This tutorial will guide you on how to get month-wise data from the MySQL database and display it on a google column chart in CodeIgniter 4 app.

How to Create Google Bar/Column Charts in Codeigniter 4

Let’s follow the following steps to implement google charts in codeIgniter 4 apps with MySQL database:

  • Step 1: Setup Codeigniter 4 Project
  • Step 2: Basic Configurations
  • Step 3: Create Table in Database
  • Step 4: Setup Database Credentials
  • Step 5: Create a Controller
  • Step 6: Create a View
  • Step 7: Define Routes
  • 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 column chart app 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', '2019-03-01'),
  (4, 'Editor', '[email protected]', '9000000004', '2019-04-01'),
  (5, 'Writer', '[email protected]', '9000000005', '2019-05-01'),
  (6, 'Contact', '[email protected]', '9000000006', '2019-06-01'),
  (7, 'Manager', '[email protected]', '9000000007', '2019-07-01'),
  (8, 'John', '[email protected]', '9000000055', '2019-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 a Controller

In this step, Visit app/Controllers and create a controller name GoogleChart.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 GoogleChart extends Controller
{

    public function index() {

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

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

       $record = $query->getResult();

       $output = [];

      foreach($record as $row) {
            $output[] = array(
             'month_name'   => $row->month_name,
             'count'  => floatval($row->count)
            );
      }

      $data['output'] = ($output);
        
	  return view('home',$data);
    }

}

Step 6: Create a 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>Codeigniter 4 Google Column Chart</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 id="container" style="width: 550px; height: 400px; margin: 0 auto"></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">
    function drawChart() {

        /* Define the chart to be drawn.*/
        var data = google.visualization.arrayToDataTable([
            ['Month', 'Users Count'],
            <?php 
             foreach ($output as $row){
             echo "['".$row['month_name']."',".$row['count']."],";
             }
             ?>
        ]);
        var options = {
            title: 'Month Wise Registered Users Of Current Year <?php echo date("Y")?>',
            isStacked: true
        };
        /* Instantiate and draw the chart.*/
        var chart = new google.visualization.ColumnChart(document.getElementById('container'));
        chart.draw(data, options);
    }
    google.charts.setOnLoadCallback(drawChart);
</script>

Step 7: Define Routes

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('/', 'GoogleChart::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

Codeigniter 4 google column charts example. In this tutorial, you have learned how to create google column charts with codeigniter 4 and mysql

Recommended Codeigniter Tutorials

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

[ad_2]

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.

GSTIN is 03EGRPS4248R1ZD.

Contact
Jassweb, Rai Chak, Punjab, India. 143518
Item added to cart.
0 items - 0.00