MySQL Group By in CodeIgniter 4 Query Builder Tutorial

Share this Article
Reading Time: 7 minutes
320 Views

CodeIgniter 4 provides the complete set of Query builder methods to use in querying database. Inside this article we will see the concept of MySQL group by in codeigniter 4 Query Builder.

In Query builder to do group by we have a method available. Group By helps us to get data with a group and even we can count number records on that group.

Learn More –

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.


Create Database & Table in Application

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE codeigniter4_app;

Next, we need a table. That table will be responsible to store data. Let’s create a table with some columns.

CREATE TABLE `students` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(50) NOT NULL,
 `marks` int(11) NOT NULL,
 `status` enum('pass','fail','average') NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Successfully, we have created a database and a table.


Dump Test Data To Table

Open MySQL database and run this command to insert test data into table.

--
-- Dumping data for table `students`
--

INSERT INTO `students` (`id`, `name`, `marks`, `status`) VALUES
(1, 'Student 1', 430, 'average'),
(2, 'Student 2', 520, 'pass'),
(3, 'Student 3', 390, 'fail'),
(4, 'Student 4', 510, 'pass'),
(5, 'Student 5', 430, 'average'),
(6, 'Student 6', 510, 'pass'),
(7, 'Student 7', 370, 'fail');

Here, we have few rows taking to understand the concept of group by. You can consider many more rows.


CodeIgniter 4 Group By Method

In CodeIgniter 4, groupBy() named method available to do group queries.

$builder->groupBy(ColumnName)

Example #1

Task

We want to create a group of Total students by marks wise

MySQL Query

SELECT count(id) as total_students, marks FROM students group by marks

Writing in CodeIgniter 4

We will use query builder methods for this.

<?php

namespace App\Controllers;

class Home extends BaseController
{
	public function __construct()
	{
		$this->db = db_connect();
	}

	public function index()
	{
		$builder = $this->db->table("students");

		$builder->selectCount('id','total_students');
		$builder->select('marks');
		$builder->groupBy('marks');
		$query = $builder->get();

		echo "<pre>";
		print_r($query->getResult());
      
        // To get last query executed
        // $this->db->getLastQuery();
	}
    
    //...
}

Behind the scene it will generate query as –

SELECT COUNT(`id`) AS `total_students`, `marks` FROM `students` GROUP BY `marks`

If we run this query to MySQL –

Output To Browser

Example #2

Task

We want to create a group of Total students by status wise, means how many student are pass, fail or an average.

MySQL Query

SELECT count(id) as total_students, status FROM students group by status

Writing in CodeIgniter 4

We will use query builder methods for this.

<?php

namespace App\Controllers;

class Home extends BaseController
{
	public function __construct()
	{
		$this->db = db_connect();
	}

	public function index()
	{
		$builder = $this->db->table("students");

		$builder->selectCount('id','total_students');
		$builder->select('status');
		$builder->groupBy('status');
		$query = $builder->get();

		echo "<pre>";
		print_r($query->getResult());
      
        // To get last query executed
        // $this->db->getLastQuery();
	}
    
    //...
}

Behind the scene it will generate query as –

SELECT COUNT(`id`) AS `total_students`, `status` FROM `students` GROUP BY `status`

If we run this query to MySQL –

Output To Browser

Example #3

Task

We want to create a group Total students by marks and status wise

MySQL Query

SELECT count(id) as total_students, marks, status FROM `students`group by marks, status

Writing in CodeIgniter 4

We will use query builder methods for this.

<?php

namespace App\Controllers;

class Home extends BaseController
{
	public function __construct()
	{
		$this->db = db_connect();
	}

	public function index()
	{
		$builder = $this->db->table("students");

		$builder->selectCount('id','total_students');
		$builder->select('marks, status');
		$builder->groupBy(['marks', 'status']);
		$query = $builder->get();

		echo "<pre>";
		print_r($query->getResult());
      
        // To get last query executed
        // $this->db->getLastQuery();
	}
    
    //...
}

Behind the scene it will generate query as –

SELECT COUNT(`id`) AS `total_students`, `marks`, `status` FROM `students` GROUP BY `marks`, `status`

If we run this query to MySQL –

Output To Browser

We hope this article helped you to learn MySQL Group By in CodeIgniter 4 Query Builder Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on CodeIgniter 4 here

Leave a Comment