/    Sign up×
Community /Pin to ProfileBookmark

Searching database "foreach" statement

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

[QUOTE]

$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 .= “))”;
}

[/QUOTE]

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@cridleyOct 23.2007 — 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 .= ")";
[/CODE]
×

Success!

Help @sac8513 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...