Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter DB Query with where, or, and.. and like

I have a query the conditions of it below (minus select, from, etc)

$this->db->where('show_year', $yyyy);
$this->db->or_where('idn', $idn);
$this->db->or_like('post_slug', $idn);

which forms

SELECT * FROM (`nyb_articles`) 
WHERE `show_year` = '2009' 
OR `idn` = 'the' 
AND `post_slug` LIKE '%the%'

However I am looking to have it be more like

SELECT * FROM (`nyb_articles`) 
WHERE `show_year` = '2009' 
AND (`idn` = 'the' OR `post_slug` LIKE '%the%')

My problem is Im not sure if CI's active record supports this notion, and if it does, how would I tackle it, as I can't find notion of it anywhere in the docs. No matter how I change up the like, or_like, where, or_where I can't even nail something similar. So anyone got any ideas? I'd prefer to stay away from a raw query if at all possible, but if I have to prepare one and do it that way, I will, just prefer not to.

like image 620
chris Avatar asked Nov 18 '12 10:11

chris


People also ask

How do you like in CI?

In codeigniter framework, we have to use the function $this->db->like(); to generate the LIKE clause. It should be used along with codeigniter select query to automatically generate where and like operators. Code igniter also supports several variations of like clause which we'll see later in this article.

Does CodeIgniter prevent SQL injection?

CodeIgniter's Active Record methods automatically escape queries for you, to prevent sql injection. $this->db->insert('tablename', array('var1'=>$val1, 'var2'=>$val2)); If you don't want to use Active Records, you can use query bindings to prevent against injection.


1 Answers

Did you try this?

SELECT * FROM (`nyb_articles`) 
WHERE `show_year` = '2009' AND `idn` = 'the' 
OR `show_year`='2009' AND `post_slug` LIKE '%the%'

I think the following produces expression above:

$this->db->select(...)->from(...)->
where("show_year","2009")->where("idn","the")->
or_where("show_year","2009")->like("post_slug","%the%")
like image 168
uzsolt Avatar answered Oct 06 '22 20:10

uzsolt