Jump to content

Exclude fields from search query if nothing is entered


Eiolon

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.

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;

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.