Jump to content

Exclude fields from search query if nothing is entered


Go to solution Solved by Barand,

Recommended Posts

So I have a search form that has multiple fields.  All the fields are optional, however, I want users to be able to narrow things down by entering some or all if desired.

 

What I don't know how to do is exclude a field from the search query if nothing is entered.

 

So the form is setup as:

 

Subject: select

Topic: text

Title: text

Year: select

Location: text

Type: text

 

Current search query and PHP:

$subject = $_GET['subject'];
$topic = $_GET['topic'];
$title = $_GET['title'];
$year = $_GET['year'];
$location = $_GET['location'];
$type = $_GET['type'];

$sth = $dbh->prepare("
	SELECT 
		*
	FROM
		periodic
	WHERE
		SUBJECT = :subject
	AND
		TOPIC = :topic
	AND
		TITLE = :title
	AND
		YEAR = :year
	AND
		LOCATION = :location
	AND
		TYPE = :type
");
$sth->bindParam(':subject', $subject);
$sth->bindParam(':topic', $topic);
$sth->bindParam(':title', $title);
$sth->bindParam(':year', $year);
$sth->bindParam(':location', $location);
$sth->bindParam(':type', $type);
$sth->execute();

Obviously the initial query is requiring something in each field with the AND operator and unfortunately, unless the field actually is NULL any field left blank will throw off the results.

 

Thanks for your pointers.

  • Solution

I use this method

$where = array();
$whereclause = '';

if ($subject != '') {
    $where[] = "SUBJECT = :subject";
}
if ($topic != '') {
    $where[] = "TOPIC = :topic";
}
if ($title != '') {
    $where[] = "TITLE = :title";
}

if (count($where) > 0) {
    $whereclause = " WHERE " . join(' AND ', $where);
}

$sql = "SELECT * FROM periodic" . $whereclause;
Edited by Barand
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.