CodeIgniter Forums
Active record where/or_where question? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: Active record where/or_where question? (/thread-9432.html)



Active record where/or_where question? - El Forum - 06-25-2008

[eluser]JasonS[/eluser]
This is what I have at the moment.

Code:
$this->db->where('id', $id);
$this->db->or_where('winner', $this->session->userdata('id'));
$this->db->or_where('author', $this->session->userdata('id'));

I want to look for the following

id is equal to $id
where user is either winner or author

How do I do this with the active record class?


Active record where/or_where question? - El Forum - 06-25-2008

[eluser]xwero[/eluser]
The problem is the AR library has no option to add parenthesis so the where part of the snippet you provided will output
WHERE id = 1 OR winner = 1000 OR author = 1000
But you want
WHERE id = 1 AND (winner = 1000 OR author = 1000)

To make it happen and escape the data to prevent sql attacks at the same time you will have to do
Code:
$session_id = $this->db->escape($this->userdata->item('id'));
$where = sprintf('id = %d AND (winner = %d OR author = %d)', $this->db->escape($id),$session_id,$session_id);
$this->db->where($where);



Active record where/or_where question? - El Forum - 06-25-2008

[eluser]JasonS[/eluser]
Thanks xwero, I will give that a go. To confirm on another matter. If data is entered via active record it is automatically escaped right?


Active record where/or_where question? - El Forum - 06-25-2008

[eluser]xwero[/eluser]
If you use the methods as mentioned in the userguide they are escaped. If you use a string as parameter you are on your own escaping the values.


Active record where/or_where question? - El Forum - 06-25-2008

[eluser]JasonS[/eluser]
Thats what I thought. Thanks for all your help.