Sonex Sonex - 4 years ago 161
SQL Question

Code Igniter - MySQL query using where and like

I have searched every answer but nothing describes what I want or maybe I didn` t comprehend them quite right. So here goes my question. 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 code igniter?
$propertyValue, $someValue, $offsetValue
are all php variables. And of course I need to avoid sql injection. I have also tested this in phpmyadmin and my query works fine.

Answer Source

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');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download