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
https://forums.phpfreaks.com/topic/62100-quick-where-query-question/
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.

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.