Welcome Guest, Not a member yet? Register   Sign In
mysql query "where like array of value" - need help
#1

[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%' ";
#2

[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.
#3

[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.
#4

[eluser]new_igniter[/eluser]
Thanks!
#5

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

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

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

[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.




Theme © iAndrew 2016 - Forum software by © MyBB