MySQL Order By in CodeIgniter 4 Query Builder Tutorial

Reading Time: 5 minutes
12,875 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 Order By in codeigniter 4 Query builder.

In Query builder to use Order By we have a method available. Order by helps us to get data with a certain order like ascending or descending

The ORDER BY keyword is used to sort the result-set in ascending or descending order.

The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

Learn More –

Let’s get started.


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,
 `email` varchar(50) NOT NULL,
 `phone_no` varchar(15) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Successfully, we have created 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`, `email`, `phone_no`) VALUES
(1, 'Sanjay Kumar', 'sanjay_kumar@gmail.com', '8527419630'),
(2, 'Sanjay Mishra', 'sanjaymishra1001@yahoo.com', '7456321089'),
(3, 'Rahul Khanna', 'rahulkhanna@yahoo.com', '9632145870'),
(4, 'Vijay Singh', 'vijay_singh@gmail.com', '7896541230'),
(5, 'Suraj Lal', 'suraj_lal@outlook.com', '7894563210'),
(6, 'Dhananjay Kumar', 'dhananjay_kumar@outlook.com', '8529633217');

Here, we have few rows taking to understand the concept of orderBy() method. You can consider many more rows.


CodeIgniter 4 Order By Method

In CodeIgniter 4, orderBy() named method available for order specific.

$builder->orderBy('column_name','ASC | DESC | RANDOM')

Example #1 Using Query Builder (DESC)

Task

We want to list all students order by name in descending order.

MySQL Query

SELECT * FROM students order by name DESC

Writing in CodeIgniter 4

We will use Query builder –

<?php

namespace App\Controllers;

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

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

		$builder->select('*');
		$builder->orderBy('name', 'DESC');
		$query = $builder->get();

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

Example #2 Using Query Builder (ASC)

Task

We want to list all students order by name in ascending order.

MySQL Query

SELECT * FROM students order by name ASC

Writing in CodeIgniter 4

$builder = $this->db->table("students");

$builder->select('*');
$builder->orderBy('name');
$query = $builder->get();

As, you can see we have used $builder->orderBy(‘name’); Optionally if we want ASC into second value, it is also Ok.

$builder = $this->db->table("students");

$builder->select('*');
$builder->orderBy('name', 'ASC');
$query = $builder->get();

Example #3 Using Query Builder (RANDOM)

Task

We want to list all students order by name in random order. It will provide you the data in random order. It uses MySQL RAND() function.

MySQL Query

SELECT * FROM `students` ORDER BY RAND()

Writing in CodeIgniter 4

$builder = $this->db->table("students");

$builder->select('*');
$builder->orderBy('name', 'random');
$query = $builder->get();

Example #4 Using Model (ASC)

Task

We want to list all students order by name in ascending order.

Writing in CodeIgniter 4

$studentObj = new Student();

$studentObj->orderBy('name', 'ASC')->findAll();

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

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

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.