/    Sign up×
Community /Pin to ProfileBookmark

Search mySQL DB with any number of optional terms

First time writing this type of script. I thought I’d share it and see if anyone has suggestions for improvement (it works). Hopefully the comments are clear enough. Thanks!

[code=php]
<?php if ( isset($_POST[‘submit’]) ) {

$rec_number = 1;
$count = 0;
$query = “SELECT * FROM properties WHERE “; //the sql query will be build on this
unset($_POST[‘submit’]); //detele this key because it throws off the calculations

foreach ( $_POST as $key => $value ) { //the keys of this varible must match the equivalent db columns to be searched

if ( $value != “” ) { //Do this with every search item that has a value

$count=$count+1;

if ( $count == 1 ) { //one term search does not require AND and must be handled separately
$query = $query . “$key=’$value'”;
}
else { //Multiple terms require the AND in between terms and builds on the one term search
$query = $query . ” AND $key=’$value'”;
}

}

}

//run query
if ( $count == 0 ) { //if there are no search terms, say so
echo “There are no search terms!”;
} ELSE { //run it

//optionally, add and ORDER BY option here to reorder the results,
//or even include that option in the search form and then append it to the query here
//but it will complicate the counting routine

$query = $query.”;”;
$result = mysql_query($query);
include ‘display_results.php’;

} ?>

[/code]

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@hyperionXSJun 04.2012 — The perfect environment for SQL injection...
Copy linkTweet thisAlerts:
@robahasauthorJun 04.2012 — Thanks for that reminder... I'm going to control that with user sql user privileges.
×

Success!

Help @robahas 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 12.9,
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: @bahaedd,
tipped: article
amount: 1000 SATS,

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

tipper: @mbsaad,
tipped: article
amount: 1000 SATS,
)...