foreach in select statement how to put "AND" in loop

Discussion in 'PHP' started by gilgalbiblewheel, Sep 21, 2008.

  1. #1
    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:

     
    gilgalbiblewheel, Sep 21, 2008 IP
  2. LogicFlux

    LogicFlux Peon

    Messages:
    2,925
    Likes Received:
    102
    Best Answers:
    0
    Trophy Points:
    0
    #2
    
    
    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.
     
    LogicFlux, Sep 21, 2008 IP
  3. zerxer

    zerxer Peon

    Messages:
    368
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    0
    #3
    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:
     
    zerxer, Sep 21, 2008 IP