Jump to content

Posting values to query SQL


petenaylor

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/247975-posting-values-to-query-sql/
Share on other sites

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.