/    Sign up×
Community /Pin to ProfileBookmark

Show all records if nothing selected from drop down

Hi All,

Kinda new to this. I’ve got a MySQL search query working using 2 drop downs, so if white and mermaid or ivory and fishtail is selected, the results are returned successfully. I can’t figure out how to get every color/style to display if nothing is selected in one of the dropdowns. So just selecting ‘white’ should return all white fishtails and mermaids. Any help would be really appreciated ? I’ve put a demo here to show what I mean [url]http://goo.gl/E4vzuM[/url]

[code=php]
// Snippet from my PHP…

if (isset($_REQUEST[‘submit’]))
{ // Show results from dropdowns
$drop1 = $_POST[‘search1’];
$drop2 = $_POST[‘search2’];
$query_all = “SELECT * FROM products WHERE `colour` LIKE ‘%”.$drop1.”%’ AND `style` LIKE ‘%”.$drop2.”%'”;
}
else // Show all
{
$query_all = “SELECT * FROM products”;
}
[/code]

[code=html]
<select name=”search1″ id=”search1″>
<option value=”” selected=”selected”>Please Select</option>
<option value=”white”>white</option>
<option value=”ivory”>ivory</option>
</select>

<select name=”search2″ id=”search2″>
<option value=”” selected=”selected”>Please Select</option>
<option value=”fishtail”>fishtail</option>
<option value=”mermaid”>mermaid</option>
</select>

<input name=”submit” type=”submit” value=”Submit”/>
[/code]

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@bionoidNov 27.2013 — Untested, but what about:

[code=php]$query_all = 'SELECT * FROM products WHERE 1=1' . ($drop1 ? ' AND colour LIKE "%' . $drop1 . '%"' : '') . ($drop2 ? ' AND style LIKE "%' . $drop2 . '%"' : '');[/code]

Don't forget to escape your user input to prevent SQL injections.
Copy linkTweet thisAlerts:
@drennanauthorNov 27.2013 — Awesome, thank you. Not sure what escaping is but I'll have a read up on it. Thanks again ?
Copy linkTweet thisAlerts:
@drennanauthorNov 27.2013 — didn't think that was needed with drop downs but looks like some tools can allow user input. Thanks for the heads up
Copy linkTweet thisAlerts:
@bionoidNov 27.2013 — Don't trust your data, always sanitise. ?

Use [FONT=Courier New]mysql_real_escape_string[/FONT] if you haven't already discovered it.
×

Success!

Help @drennan 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.4,
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: @Yussuf4331,
tipped: article
amount: 1000 SATS,

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

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