Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter $this->db->order_by(' ','desc') result is not complete

I want to sort my database values in descending order using this query below in my model. However, it doesn't completely sort in descending order all the values in the database but when ascending is used, it works well.

function sort_all_courses_desc($tennant_id)
{
    $this->db->select('*');
    $this->db->where('tennant_id',$tennant_id);
    $this->db->order_by("course_name","desc");
    $this->db->from('courses');
    $query=$this->db->get();
    return $query->result();
}
like image 479
Eli Avatar asked Mar 07 '13 13:03

Eli


3 Answers

Put from before where, and order_by on last:

$this->db->select('*');
$this->db->from('courses');
$this->db->where('tennant_id',$tennant_id);
$this->db->order_by("UPPER(course_name)","desc");

Or try BINARY:

ORDER BY BINARY course_name DESC;

You should add manually on codeigniter for binary sorting.

And set "course_name" character column.

If sorting is used on a character type column, normally the sort is conducted in a case-insensitive fashion.

What type of structure data in courses table?

If you frustrated you can put into array and return using PHP:

Use natcasesort for order in "natural order": (Reference: http://php.net/manual/en/function.natcasesort.php)

Your array from database as example: $array_db = $result_from_db:

$final_result = natcasesort($array_db);

print_r($final_result);
like image 62
Marin Sagovac Avatar answered Nov 16 '22 02:11

Marin Sagovac


$this->db1->where('tennant_id', $tennant_id);
$this->db1->order_by('id', 'DESC');
return $this->db1->get('courses')->result();
like image 25
Narottam Sahoo Avatar answered Nov 16 '22 03:11

Narottam Sahoo


Put the line $this->db->order_by("course_name","desc"); at top of your query. Like

$this->db->order_by("course_name","desc");$this->db->select('*');
$this->db->where('tennant_id',$tennant_id);
$this->db->from('courses');
$query=$this->db->get();
return $query->result();
like image 26
fazalerabbi Avatar answered Nov 16 '22 02:11

fazalerabbi