Jump to content

Quick Where Query Question


iceblox

Recommended Posts

Hi Guys,

 

Im going to be doing a search page with loads of drops downs but my question is if they leave one blank how can i get php not to pick it up.

 

So my query will look like this

 

$query = "SELECT * FROM Makes WHERE MakeName ='$Postblah' MakeSpud = '$Postblah'";

 

How would i make it work so if someone doesnt enter a MakeSpud php shows all MakeSpuds?

 

 

Phil

Link to comment
Share on other sites

Well, if you name all of your form inputs with the same name as their corresponding field names in the database, then you can do this:

 

<?php
$fields = array('field1','field2','field3');//an array containing all of the possible fields to search by
$where = '';//define the variable
foreach($fields as $v){
    if(!empty($_POST[$v])){
        $where .= $v.' = '.$_POST[$v].' AND ';
    }
}
$where = substr($where,0,strlen($where)-5);//stip out the last 'and'
$query = "SELECT * FROM Makes WHERE $where";
?>

 

The idea is that you build the WHERE part of your query based on the input, and you only add a particular field if there is some data to search by.

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.