CodeIgniter Forums
mysql query "where like array of value" - need help - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: mysql query "where like array of value" - need help (/showthread.php?tid=13789)



mysql query "where like array of value" - need help - El Forum - 12-05-2008

[eluser]new_igniter[/eluser]
Can someone help me to understand the syntax for this mySql query

$matchesArray = array('love','like','happy');
$query = "SELECT * FROM column where content like '%$matchesArray%' ";


mysql query "where like array of value" - need help - El Forum - 12-05-2008

[eluser]new_igniter[/eluser]
I should have mentioned this does NOT work, obviously and I need help to know how to do a query like that.


mysql query "where like array of value" - need help - El Forum - 12-05-2008

[eluser]Pascal Kriete[/eluser]
You can chain LIKE clauses using AND and OR. In this case OR is probably more appropriate:
Code:
$field = 'content';
$matches = array(‘love’,‘like’,‘happy’);

// TODO: check if matches has content

$first = array_pop($matches);
$query = "WHERE {$field} LIKE '%{$first}%' ";

foreach($matches as $match)
{
     $query .= "OR {$field} LIKE '%{$match}%' ";
}

You may want to consider looking at the active record or_like function. If you don't use active record, remember to sanitize the matches array.


mysql query "where like array of value" - need help - El Forum - 12-05-2008

[eluser]new_igniter[/eluser]
Thanks!


mysql query "where like array of value" - need help - El Forum - 12-05-2008

[eluser]xwero[/eluser]
i would go for the AR where_in method
Code:
$this->db->where_in('field',$array);



mysql query "where like array of value" - need help - El Forum - 12-05-2008

[eluser]new_igniter[/eluser]
ah, thats rad.


mysql query "where like array of value" - need help - El Forum - 12-05-2008

[eluser]new_igniter[/eluser]
ah very cool!


mysql query "where like array of value" - need help - El Forum - 12-08-2008

[eluser]Jon L[/eluser]
This may no longer be true, but I read a year or two ago that the sql IN statement is often slower than a (this LIKE that OR this2 LIKE that2...). You may want to check to see if that's still true.