www.webdeveloper.com
Results 1 to 2 of 2

Thread: Searching database "foreach" statement

  1. #1
    Join Date
    Dec 2006
    Posts
    177

    Searching database "foreach" statement

    Does anyone know why I keep getting an error with this "foreach" statement

    $query = "SELECT * FROM `tablinfo` WHERE ("; /* Notice that the
    query ends here for now*/

    foreach($trimmed_array as $kw){


    if (!is_array($trimmed))
    {
    $kw = $trimm = str_replace(",", " ", $kw);
    //echo "and kw is ".$kw. " ";
    }


    if (!is_array($trimmed))
    {
    $first_trim = str_replace(",", " ", $trimmed_array['0']);
    }


    if($first_trim != $kw){ //this is used in case there's more than one keyword
    $query .= "OR (";}
    /*
    <-----Notice that we may add an OR to the SQL if there is more than one keyword in the search
    */
    //I use privacy = '0' because some of the users may choose to make their data private.

    $query .= "`privacy` = '0' AND (`title` LIKE '%$kw%' OR `description` LIKE '%$kw%' OR `keywords` LIKE '%$kw%' "; //in SQL, the % is like * for Linux
    $query .= "))";
    }

  2. #2
    Join Date
    Jun 2006
    Posts
    384
    What's the error? That code looks pretty flawed from where I'm sitting though..

    What is $trimmed and why are you doing the same check twice:

    if (!is_array($trimmed))

    ?

    Without knowing what $trimmed is for, i'd go with something like :

    Code:
    $query = "SELECT * FROM `tablinfo` WHERE privacy='0' "; 
    
    $i = 0;
    foreach($trimmed_array as $kw)
    {
    	$kw = $trimm = str_replace(",", " ", $kw);
    
    
    	if($i > 0)//this is used in case there's more than one keyword
    		$query .= " OR ";	
    	else	//the first time round it's an and
    		$query .= " AND (";
    	
    
    	$query .= " `title` LIKE '%$kw%' OR `description` LIKE '%$kw%' OR `keywords` LIKE '%$kw%' ";
    
    	//increment $i so next time it knows it not the first 
    	$i++;
    }  
    $query .= ")";

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles