Reputation: 695
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.
Upvotes: 3
Views: 752
Reputation: 47874
select('*')
is safe to omit, because the default SELECT clause is SELECT *
.where()
, from()
, limit()
and offset()
method calls can all be combined into a get_where()
call.group_start()
and group_end()
to encapsulate the OR LIKE condition logic.or_like()
can receive an associative array in its first parameter (just remember that keys must not be repeated).id
might be.return $this->db
->group_start()
->or_like(['id' => $someValue, 'name' => $someValue, 'description' => $someValue])
->group_end()
->order('id', 'DESC')
->get_where('MyTable', ['PropertyA' => $propertyValue], $limit, $offset)
->result();
Upvotes: 0
Reputation: 22532
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');
Upvotes: 9