thomasward1212
thomasward1212

Reputation: 23

Putting an IF statement in SQL query if user has supplied data in that field

I have a SQL query, where imputs are generated by the user via a search form. What I have at the moment is this.

// Select some data
$sth = $dbh->prepare("SELECT `id`, `type_code`, `connector_type`, `construction_type`,  `author`, `estimate_lead_time`, `last_update`, `confidence_level`, `start_passband`, `stop_passband`, `low_passband`, `high_passband` 
                      FROM `filter_bandpass` 
                      WHERE (`start_passband` = $lowfreq AND `stop_passband` = $highfreq)");

I'm trying to get it to allow users to only fill out the $lowfreq and leave the $highfreq blank, and the results will show all results where $lowfreq = to user inserted data, but when they do imput an amount for $highfreq the result shows both.

Upvotes: 0

Views: 46

Answers (1)

Thorsten Kettner
Thorsten Kettner

Reputation: 95053

So either $highfreq contains data or is empty. Then simply replace

WHERE (`start_passband` = $lowfreq AND `stop_passband` = $highfreq)");

with

WHERE (`start_passband` = $lowfreq AND (`stop_passband` = $highfreq OR $highfreq = ''))");

Upvotes: 1

Related Questions