CodeIgniter Order By Query Example

Today, We want to share with you order by codeigniter.In this post we will show you Codeigniter OrderBy Query not Working, hear for orderBy Query we will give you demo and example for implement.In this post, we will learn about Sort Query Order By In Codeigniter Examples with an example.

Codeigniter OrderBy Query

Codeigniter Order By Query ASC Example

$this->db->from('my_shop');
$this->db->order_by("column1 asc,column2 asc");
$query = $this->db->get(); 
return $query->result();

Codeigniter Order By Query DESC Example

$this->db->from('my_shop');
$this->db->order_by("column1 desc,column2 desc");
$query = $this->db->get(); 
return $query->result();

Example

$this->db->select('*');
$this->db->from('tbl_Members');
$this->db->order_by('MemberName');
$query = $this->db->get();
return $query->result();

// Produces SQL
// SELECT * FROM tbl_Members ORDER BY MemberName;

CodeIgniter Order By Desc:

$this->db->select('*');
$this->db->from('tbl_Members');
$this->db->order_by('Cart', 'desc');
$query = $this->db->get();
return $query->result();

// Produces SQL
// SELECT * FROM tbl_Members ORDER BY Cart desc;

CodeIgniter Order By Two Columns:

You can also sort records using more than one column. This code igniter query sorts the table ‘Members’ with two columns, first in descending order of ‘Level’ and then ascending order of ‘MemberName’.

$this->db->select('*');
$this->db->from('tbl_Members');
$this->db->order_by('Level', 'desc');
$this->db->order_by('MemberName', 'asc');
$query = $this->db->get();
return $query->result();

// Produces SQL
// SELECT * FROM tbl_Members ORDER BY Level desc, MemberName asc;

Method Chaining in CodeIgniter:

$this->db->select('*')->from('tbl_Members')->order_by('Level desc, MemberName asc');
$query = $this->db->get();
return $query->result();

// Produces SQL
// SELECT * FROM tbl_Members ORDER BY Level desc, MemberName asc;

CodeIgniter Order By Limit:

$this->db->order_by('Level', 'asc');
$query = $this->db->get('tbl_Members', 3, 1);
return $query->result();

// Produces SQL
// SELECT * FROM tbl_Members ORDER BY Level ASC LIMIT 1, 3;

I hope you get an idea about order by codeigniter.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.