PHP Codeigniter 4 Morris Bar & Stacked Chart Tutorial

Codeigniter 4 morris bar and stacked charts example. In this step by step guide, we will explain how to implement morris stacked and bar chart in the Codeigniter application.

We will demonstrate how to fetch month-wise data from the MySQL database and blend it into the morris bar and stacked chart.

Morris js library adds significant value in implementing charts and graphs in a web application. In this Codeigniter morris bar and stacked chart tutorial, you will learn how to use Codeigniter SQL queries to integrate morris charts in the Codeigniter application pretty easily.

How to Integrate Morris Bar and Stacked Chart in Codeigniter 4 using MySQL

  • Step 1: Download Codeigniter Project
  • Step 2: Update Database Details
  • Step 3: Create Database and Table
  • Step 4: Make Controller File
  • Step 5: Register Route
  • Step 6: Create View File
  • Step 7: Run App in Browser

Download Codeigniter Project

The following url will open the gateway to the official site, you can download the latest version of the Codeigniter app.

https://www.codeigniter.com/download

Second method to download the app is by using the Composer command, make sure to set up the Composer tool.

composer create-project codeigniter4/appstarter

Update Database Details

To make the app connection with the database, you have to add the database details into the app/Config/Database.php file.

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'db_username',
        'password' => 'db_password',
        'database' => 'db_name',
        '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,
    ];

Create Database and Table

In this step, you have to run the provided command to create a new database, new table and add the data into the database.

CREATE TABLE `users` (
  `id` int(11) NOT NULL COMMENT 'Primary Key',
  `name` varchar(255) NOT NULL COMMENT 'name',
  `sales` varchar(55) NOT NULL COMMENT 'sales',    
  `created_at` varchar(30) NOT NULL COMMENT 'created at'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='user db';

INSERT INTO `users` (`id`, `name`, `sales`, `created_at`) VALUES
(1, 'Marie Merritt', '2000', '2020-01-02'),
(2, 'Shoshana Jones', '3000', '2020-02-03'),
(3, 'Rickey Peed', '1000', '2020-03-02'),
(4, 'Sean Walker', '2500', '2020-04-05'),
(5, 'Patrick Frazier', '6000', '2020-05-04'),
(6, 'Neil Chevalier', '27000', '2020-06-07'),
(7, 'James Jackson', '1600', '2020-07-05'),
(8, 'Kayla George', '1200', '2020-08-06');

Make Controller File

In this section, you have to create the controller file and insert the functions to load the chart data from the database and display it into the chart using the SQL query.

Update code in app/Controllers/GraphController.php file.

<?php 

namespace App\Controllers;
use CodeIgniter\Controller;


class GraphController extends Controller
{
    public function index() {
        return view('index');
    }
    
    public function showGraph() {
        
        $db = \Config\Database::connect();
        $builder = $db->table('users');

        $query = $builder->select("COUNT(id) as count, sales as s, MONTHNAME(created_at) as month");
        $query = $builder->orderBy("s ASC, month ASC");
        $query = $builder->where("MONTH(created_at) GROUP BY MONTHNAME(created_at), s")->get();
        $record = $query->getResult();

        $usersData = [];

        foreach($record as $row) {
            $usersData[] = array(
                'month'   => $row->month,
                'sales' => floatval($row->s)
            );
        }
        
        $data['usersData'] = ($usersData);    
        return view('index', $data);                
    }
}

Register Route

You can use this route to view the pie graph in the Codeigniter app.

Now, you have to go to app/Config/Routes.php, and in this file, you have to create a new route.

/*
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
*/

$routes->get('/show-chart', 'GraphController::showGraph');

Create View File

In this section, we will create index.php file inside the app/Views folder and then you have to add the provided code into the app/Views/index.php file.

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">

	<title>Codeigniter Morris Bar Chart Example</title>

	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
	<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
	<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
	<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
	<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
</head>

<body>

	<body>
		<div class="container mt-4">
			<div>
				<h2 class="mb-3">Morris Bar Chart in Codeigniter</h2>
				<div id="barGraph" style="width: 100%; height: 500px"></div>
			</div>
			<div>
				<h2 class="mb-3">Morris Stacked Chart in Codeigniter</h2>
				<div id="stackedGraph" style="width: 100%; height: 500px"></div>
			</div>
		</div>


		<script>
			var serries = <?php echo json_encode($usersData);?> ;
			var data = serries,
				config = {
					data: <?php echo json_encode($usersData); ?>,
					xkey : 'month',
					ykeys: ['sales'],
					fillOpacity: 0.8,
					hideHover: 'auto',
					resize: true,
					behaveLikeLine: true,
					stacked: true,
					barColors: "232",
					labels: ['Users months wise']					
				};

			config.element = 'stackedGraph';
			config.stacked = true;
			Morris.Bar(config);

			config.element = 'barGraph';
			Morris.Bar(config);			
		</script>
	</body>

</html>

Run App in Browser

In the last section, you have to run the provided command to start the Codeigniter development server.

php spark serve

Once the codeigniter server invoked, ensure that you have inserted the given url on the browser to test the the morris bar chart with dynamic data.

http://localhost:8080/show-chart

PHP Codeigniter 4 Morris Bar & Stacked Chart Tutorial

Summary

In this tutorial, you have seen how to display data dynamically on morris stacked and bar charts in Codeigniter 4 application using MySQL. We fetch users data from the database and show the data on the stacked and bar charts, and we reckon this guide will help you.