Welcome Guest, Not a member yet? Register   Sign In
How do I sort database results using multiple columns?
#1

[eluser]danfloun[/eluser]
As the question states, how can I order by first second and third column ascending.

At present I use

Code:
$this->db->select('id, company, first_name, last_name, landline_tel, mobile_tel, fax_tel, email');
        $this->db->orderby("company", "asc");
        $query = $this->db->get('clients');
        return $query->result();

but this only orders by the company column and I would like to order by the last_name column as a second sort.

Thanks

Danny
#2

[eluser]John_Betong[/eluser]
Hi Danfloun,

In the user manual (Class Reference/Dababase Class/Active Record Class) it states:

Quote:$this->db->orderby();

Lets you set an ORDER BY clause.
The first parameter contains the name of the column you would like to order by.
The second parameter lets you set the direction of the result.
Options are asc or desc or RAND()

$this->db->orderby("title", "desc");

// Produces: ORDER BY title DESC


You can also pass your own string in the first parameter:

$this->db->orderby('title desc, name asc');

// Produces: ORDER BY title DESC, name ASC
 
So your query:
Code:
$this->db->orderby("company", "asc");

// try
   $this->db->orderby("company ASC, last_name ASC");


After using the query check it by using the following:
Code:
$this->db->last_query();
   die;
#3

[eluser]danfloun[/eluser]
Thanks John_Betong,

May I ask what the checking is for?
I understand that

Code:
$this->db->last_query()

Returns the last query, so I assume the above code just checks to see if the query was successful! or more to the point, there was a result returned?

Is that right? Either way, why should I bother with that bit?

Thanks for you time.

Danny
#4

[eluser]John_Betong[/eluser]
Hi Danny,

It is not necessary to use $this->db->last_query(). It is just a means of displaying the complete SQL statement.

CodeIgniter makes it easy to create SQL statement strings. I find it is sometimes better to see the complete statement especially when the result is not what was expected.

If you are not familiar with SQL then final SQL statement would not be much use.

Just ignore it.

Cheers,

John_Betong
 




Theme © iAndrew 2016 - Forum software by © MyBB