I have a long SELECT statement with two foreach loops. But I'm not sure how to include a comma in the first foreach and the AND in the second foreach loops (of course the last value shouldn't be followed with a comma or an AND): $myarray = explode(' ', $keyword1); if($_GET['searchChap']=="searchTheChap"){ $whereclause .= " AND text_data IN ( "; foreach($myarray as $value){ $whereclause .= "'%".$value."%',"; } $whereclause .= " ) GROUP BY chapter HAVING "; foreach($myarray as $value){ $whereclause .= "SUM(CASE WHEN text_data = '%".$value."%' THEN 1 ELSE 0 END) > 0"; } } PHP:
foreach($myarray as $value){ $whereclause .= "'%".$value."%',"; } $whereclause = preg_replace('/,$/', '', $whereclause); PHP: If you run a loop that puts AND at the end, the you can put this after the loop to chop off the last AND: $whereclause = preg_replace('/and$/i', '', $whereclause); PHP: There must be no whitespace after 'and', including newlines.
Seems a bit much to use regex to just remove one item/word from the end of a string. Anyways, try this. I completely removed the need for loops. <? $myarray = explode(' ', $keyword1); if($_GET['searchChap']=="searchTheChap" && count($myarray) > 0){ $whereclause .= " AND text_data IN ('%" . implode("%','%", $myarray) . "%') GROUP BY chapter HAVING SUM(CASE WHEN text_data = '%" . implode("%' THEN 1 ELSE 0 END) > 0 AND SUM(CASE WHEN text_data = '%", $myarray) . "%' THEN 1 ELSE 0 END) > 0"; } ?> PHP: