Click to See Complete Forum and Search --> : Searching database "foreach" statement


sac8513
10-22-2007, 08:39 PM
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 .= "))";
}

cridley
10-23-2007, 10:24 AM
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 :


$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 .= ")";