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
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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.