petenaylor Posted September 27, 2011 Share Posted September 27, 2011 Hi all I have a form which takes details from drop down menus. But what I need is a wild card if someone leaves the selected option value as "all" it adjusts the SQL query to not search that cell so it brings all entries without filtering. My form looks like this: <select name="area" id="area"> <option value="all">--All areas--</option> <?php $getareas = mysql_query (" SELECT * FROM `areas` ORDER by name ASC"); while ($showareas = mysql_fetch_array($getareas)) { ?> <option value="<?php echo $showareas['id']; ?>"><?php echo $showareas['name']; ?></option> <?php } ?> </select> My SQL query looks lie this: $getads = mysql_query(" SELECT * FROM adverts WHERE categoryid = 1 AND areaid = '".$searchedarea."' AND makeid = '".$searchedmake."' AND modelid = '".$searchedmodel."' AND berth = '".$searchedberth."' AND live = 1 AND approved = 1 AND paid = 1 AND dateexpired >= '".$todaysdate."' ORDER BY seller ASC , type ASC, id ASC") or die (mysql_error()); So if they select 'all" in the drop down field, the SQL query doesn't have 'AND areaid = '".$searchedarea."'' in it? Is this possible, or can I add a wildcard into the SQL query? Many thanks Pete Quote Link to comment https://forums.phpfreaks.com/topic/247975-posting-values-to-query-sql/ Share on other sites More sharing options...
Pikachu2000 Posted September 27, 2011 Share Posted September 27, 2011 If $_POST['area'] is "all", don't include the field in the query. By setting $area_search to an empty string if the value of $_POST['area'] is 'all', it will only be in the query string if it's value is different from 'all'. $area_search = $_POST['area'] === 'all' ? '' : "AND areaid = '$searchedarea'"; //Then in the query string $query = "SELECT * FROM adverts WHERE categoryid = 1 $area_search // <--- added the new variable in place of the old comparison AND makeid = '".$searchedmake."' AND modelid = '".$searchedmodel . . . " I added the line breaks just to make it easier to follow. Quote Link to comment https://forums.phpfreaks.com/topic/247975-posting-values-to-query-sql/#findComment-1273335 Share on other sites More sharing options...
petenaylor Posted September 27, 2011 Author Share Posted September 27, 2011 Got it! Nice one, thanks! Quote Link to comment https://forums.phpfreaks.com/topic/247975-posting-values-to-query-sql/#findComment-1273349 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.