如果用户在该字段中提供了数据,则在SQL查询中放置IF语句

时间:2014-09-05 09:59:23

标签: php mysql sql pdo

我有一个SQL查询,其中输入由用户通过搜索表单生成。我现在拥有的是这个。

// 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)");

我试图让用户只填写$lowfreq并将$highfreq留空,结果会显示$lowfreq =用户插入数据的所有结果,但当他们为$highfreq输入金额时,结果显示两者。

1 个答案:

答案 0 :(得分:1)

因此$ highfreq包含数据或为空。然后简单地替换

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

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