CodeIgniter Forums
Operator precedence in SQL queries using DB class - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: Operator precedence in SQL queries using DB class (/showthread.php?tid=12680)



Operator precedence in SQL queries using DB class - El Forum - 10-27-2008

[eluser]wcaicedo[/eluser]
Hi friends, i have this question: Is there a way to specify logic operator precedence in a query using those functions available in DB class? Recently i needed something like:
Code:
"SELECT * FROM table where date = $date and (id = $id or other_id = $id)"

But i didn't find a way to specify that using $this->db->or_where() and stuff.

Any ideas? or i'm missing something here..


Thanks in advance.


Operator precedence in SQL queries using DB class - El Forum - 10-27-2008

[eluser]Praveen A P[/eluser]
Hey did you try this out? May be the SQL related stuff needs to be done through SQL itself, CI would just send the query and get the results.

Please try this out and let us know what happens?

At least, from a JAVA perspective thats true.


Operator precedence in SQL queries using DB class - El Forum - 10-28-2008

[eluser]dmiden[/eluser]
Hi!

You should use the $this->db->query() function for more complexed queries, f.ex.
Code:
$sql = "SELECT * FROM table WHERE date = ? AND (id = ? OR other_id = ?)";
$this->db->query($sql, array($date, $id, $id));
Or you could use $this->db->where() as a custom string, e.g.
Code:
$this->db->where('date', $date);
$this->db->where("(id={$id} OR other_id={$id})");
$this->db->get('table');

That'd produce the same as above.


Operator precedence in SQL queries using DB class - El Forum - 10-28-2008

[eluser]wcaicedo[/eluser]
Thanks bud, i ended up using something like the second one as a workaround, that stays then Smile. It would be a nice thing if CI included something to manage that precedence without resorting to one's custom queries...

Thanks a lot!

William.