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 –
- CodeIgniter 4 Views And Layouts Tutorial
- CodeIgniter 4 Working With Database Query
- Compare Dates and Times in CodeIgniter 4 Tutorial
- Complete CodeIgniter 4 Basics Tutorial
Let’s get started.
CodeIgniter 4 Installation
To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.
composer create-project codeigniter4/appstarter codeigniter-4
Assuming you have successfully installed application into your local system.
Environment (.env) Setup
When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env
Either we can do via renaming file as simple as that. Also we can do by terminal command.
Open project in terminal
cp env .env
Above command will create a copy of env file to .env file. Now we are ready to use environment variables.
Enable Development Mode
CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.
Open .env file from root.
# CI_ENVIRONMENT = production
// Do it to
CI_ENVIRONMENT = development
Now application is in development mode.
Create Database
To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.
We will use MySQL command to create database. Run this command into Sql tab of PhpMyAdmin.
CREATE DATABASE codeigniter4_app;
Successfully, we have created a database.
Create Database Table
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 table.
Database Connection
Open .env file from project root.
Search for DATABASE. You should see the connection environment variables into it. Put your updated details of database connection string values.
#-------------------------------------------------------------------- # DATABASE #-------------------------------------------------------------------- database.default.hostname = localhost database.default.database = codeigniter4_app database.default.username = admin database.default.password = admin database.default.DBDriver = MySQLi database.default.DBPrefix = database.default.port = 3306
Now, database successfully connected with the application.
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.