Reputation: 2564
$serach=array('abc','def','ghi');
$num=count($search);
for($n=0, $n<$num, $n++){
$sql .= LIKE % $search[$n] % OR ;
}
$sql=substr_replace($sql,"",-3);//REMOVE LAST OR
SELECT * FROM store_main WHERE name :sql...
i need pass an array into query LIKE, i have use loop to create the statement and put into the query, my question is, is any way do it without loop, so i can make my query more simple.
Upvotes: 0
Views: 67
Reputation: 3160
Use implode like so:
$serach = array('abc', 'def', 'ghi');
$sql .= "`name` LIKE '%" . implode("%' OR `name` LIKE '%", $serach) . "%' ";
produces:
`name` LIKE '%abc%' OR `name` LIKE '%def%' OR `name` LIKE '%ghi%'
OR you can use REGEXP. This one could be a bit slower depending on how many array elements you have and/or your table/database's efficiency.
$serach = array('abc', 'def', 'ghi');
$sql .= "`name` REGEXP '" . implode("|" $serach) . "' ";
produces:
`name` REGEXP 'abc|def|ghi'
Upvotes: 1
Reputation: 11065
Try
$array = array('lastname', 'email', 'phone');
echo "%".str_replace(",","% OR %",implode(",", $array))."%";
Output
%lastname% OR %email% OR %phone%
Refer implode and str-replace
Upvotes: 1