phpmysqlcodeigniterselectactiverecord

Convert SQL containing WHERE equals, multiple LIKE conditions, ORDER BY, LIMIT and OFFSET into CodeIgniter's active record


I want a "complex" query like this:

select *
from MyTable
where
    PropertyA='$propertyValue'
    and (
        id like '%$someValue%'
        or name like '%$someValue%'
        or description like '%$someValue%'
    ) 
order by id desc
limit 10
offset $offsetValue

How can I write this query in CodeIgniter active record oncluding the variables: $propertyValue, $someValue and $offsetValue.

I am particularly concerned about sql injection. I have tested my SQL in phpmyadmin and it works fine.


Solution

  • For SQL injections, using binded queries and Active records is safe, it will save you from SQL injections as the framework does all of the work of escaping vulnerable user input.

    You just write your code in Active record FOR 3.X version

    $this->db->select('*');
    $this->db->where('PropertyA', $propertyValue);
    $this->db->group_start();
    $this->db->like('id', $someValue);
    $this->db->or_like('name', $someValue);
    $this->db->or_like('description', $someValue);
    $this->db->group_end();
    $this->db->order('id','desc')
    $this->db->limit($limit, $start);// add your limit here
    $this->db->get('MyTable');