0
$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.

1
  • You can you IN clause. Commented Jan 23, 2014 at 7:02

2 Answers 2

1

Try

$array = array('lastname', 'email', 'phone');
echo "%".str_replace(",","% OR %",implode(",", $array))."%";

Output

%lastname% OR %email% OR %phone%

Refer implode and str-replace

Sign up to request clarification or add additional context in comments.

Comments

1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.