我有以下代码:
$sql = "SELECT name, address, city FROM tableA, tableB WHERE tableA.id = tableB.id"; if (isset($price) ) { $sql = $sql . ' AND price = :price '; } if (isset($sqft) ) { $sql = $sql . ' AND sqft >= :sqft '; } if (isset($bedrooms) ) { $sql = $sql . ' AND bedrooms >= :bedrooms '; } $stmt = $dbh->prepare($sql); if (isset($price) ) { $stmt->bindParam(':price', $price); } if (isset($sqft) ) { $stmt->bindParam(':price', $price); } if (isset($bedrooms) ) { $stmt->bindParam(':bedrooms', $bedrooms); } $stmt->execute(); $result_set = $stmt->fetchAll(PDO::FETCH_ASSOC);
我注意到的是我拥有的冗余的多个 IF 语句。
问题:有什么方法可以清理我的代码,以便我没有这些多个 IF 语句用于准备好的语句?
这与用户最近在我的书 SQL Antipatterns 的论坛上问我的问题非常相似。我给了他类似的答案:
$sql = "SELECT name, address, city FROM tableA JOIN tableB ON tableA.id = tableB.id"; $params = array(); $where = array(); if (isset($price) ) { $where[] = '(price = :price)'; $params[':price'] = $price; } if (isset($sqft) ) { $where[] = '(sqft >= :sqft)'; $params[':sqft'] = $sqft; } if (isset($bedrooms) ) { $where[] = '(bedrooms >= :bedrooms)'; $params[':bedrooms'] = $bedrooms; } if ($where) { $sql .= ' WHERE ' . implode(' AND ', $where); } $stmt = $dbh->prepare($sql); $stmt->execute($params); $result_set = $stmt->fetchAll(PDO::FETCH_ASSOC);