简体   繁体   中英

active record in codeigniter automatically adds quotes around where clause values

I've tried reading other posts on stackoverflow and also checked the active record documentation for ci, but i can't seem to find the answer to my question

I have the following logic in my model:

    $query = $this->db->get_where('categories', array('parent_id' => $category_id));

the sql this generates as per the last_query() method is:

SELECT * FROM ( categories ) WHERE parent_id = '8'

I need to remove the quotes around the number 8. How would I do that?

I've tried using the select statement and passing false as the second parm. So for example:

    $this->db->select('*', false);
    $this->db->from('categories');
    $this->db->where('parent_id=',$category_id);

But that didn't really change much. Any suggestions? Thank you

By default, CodeIgniter tries to predict the data type in your comparison, and use the appropriate SQL syntax accordingly. If your query is using single quotes, it might indicate that $category_id is being treated as a string rather than an integer. What happens if you try:

$this->db->select('*');
$this->db->from('categories');
$this->db->where('parent_id', (int) $category_id);

Alternatively, you can construct your own WHERE statement manually:

$this->db->where('parent_id = ' . (int) $category_id);

For MIN and MAX query I used null and false keyword to remove the quotes.

$this->db->where("$value > min_column",null,false);
$this->db->where("$value < max_column",null,false);

The idea of the methods is to auto escape to protect against SQL injections, if for some reason you don't want to you can send a raw query like this :

$q = "select * from categories where parent_id = $category_id";
$this->db->query($q)->result();

Which i find much easier. However i think you can send an extra false paremeter to disable it, something like :

  $query = $this->db->get_where('categories', array('parent_id' => $category_id),false);

FYI, if you want to send raw queries and escape them(for more complex queries) you can use :

$category_id = $this->db->escape($category_id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM