Welcome Guest, Not a member yet? Register   Sign In
Active record doesn't support ORDER BY FIELD()

as title say actually active record class does not support FIELD function in db->order_by.

The problem is that A.R. try to escape the function.


$this->db->order_by("FIELD(id, 129084,126792)");


ORDER BY FIELD(id, `129084`, `126792)`

but the correct query is:

ORDER BY FIELD(`id`, '129084', '126792')

a temporary fix (not a good fix) is:
/* Location: ./system/database/DB_active_rec.php */

function order_by($orderby, $direction = '')
        if (strpos($orderby, 'FIELD(') !== FALSE || strpos($orderby, 'FIELD (') !== FALSE)
            $this->ar_orderby[] = $orderby;
            return $this;
        // ...

Hope to see that implemented in the next version of CI.

Yeah, CI's active record doesn't work for everything, but its great for the most common things. When I encounter a problem with it like you did, I just write that particular query out from scratch and just use $db->query($query). I think thats better than hacking core files and its really such a rare occurrence unless you are doing pretty complex applications.

It would be nice if every method had the boolean option to protect identifiers or not like the select method does.

Just leaving this here to help others:

// set this to false so that _protect_identifiers skips escaping:
$this->db->_protect_identifiers = FALSE;

// your order_by line:
$this -> db -> order_by('FIELD ( products.country_id, 2, 0, 1 )');

// important to set this back to TRUE or ALL of your queries from now on will be non-escaped:
$this->db->_protect_identifiers = TRUE;

Theme © iAndrew 2016 - Forum software by © MyBB