phpmysqlcodeigniteractiverecordnatural-sort

CodeIgniter query with natural sorting in ORDER BY clause


I first checked if there any same problems like mine; I didn't find anything.

All are sorting alphanumeric column mixed with numeric data.

Here is my problem. I have a table that contain column A datas like this.

WRG-01 WRG-39 WRG-22 WRG-45 WRG-43

need to sort that as

WRG-01 WRG-22 WRG-39 WRG-43 WRG-45

This is the code I am using so far in CodeIgniter:

$data['products'] = $this->db->order_by('product_id', 'asc')->get('products');

in mysql, I can use this query to get done my work:

preg_replace("/[^\d]/", "",'product_id'), 'asc')

How to apply it to my above CodeIgniter code?

here is search funtion:

public function search()
{
    $data['title'] = 'Search Product';
    $product_name       = $this->input->get('product_name');
    $product_id         = $this->input->get('product_id');
    $product_category   = $this->input->get('product_category');
    $secondCategory     = $this->input->get('secondCategory');
    $thirdCategory  = $this->input->get('thirdCategory');

$data['category'] = $this->db->order_by('id', 'asc')->get_where('categories', ['parent' => 0]);
if($product_category != '')
{
    $data['secondCategory'] = $this->db->get_where('categories', ['parent' => $product_category]);
}
if($secondCategory != '')
{
    $data['thirdCategory'] = $this->db->get_where('categories', ['parent' => $secondCategory]);
}


if($product_name != '')
    {
        $this->db->like('product_name', $product_name);
    }
    if($product_id != '')
    {
        $this->db->where('product_id', $product_id);
    }
    if($product_category != '')
    {
        $this->db->where('product_category', $product_category);
    }
    if($secondCategory != '')
    {
        $this->db->where('secondCategory', $secondCategory);
    }
    if($thirdCategory != '')
    {
        $this->db->where('thirdCategory', $thirdCategory);
    }

    $data['products'] = $this->db->order_by('product_id' 'asc')->get('products');


    theme('all_product', $data);

}

I can't use sql query here because products is result array from product table.


Solution

  • Use MySQL cast

    cast(product_id as SIGNED)

    or

    cast(product_id as UNSIGNED)

    Try query like that :-

    select * from products cast(product_id as UNSIGNED) ASC|DESC