PHP:准备好的声明,需要IF语句帮助

时间:2010-04-28 20:02:47

标签: php programming-languages parameterized

我有以下代码:

$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语句?

2 个答案:

答案 0 :(得分:2)

这非常类似于用户asked最近我的书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);

答案 1 :(得分:1)

而不是if else只使用PHP三元运算符

     if (isset($_POST['statusID']))
{
  $statusID = $_POST['statusID'];
}
else
{
  $statusID = 1;

}

而不是你可以这样做:

 $statusID =  (isset($_POST['statusID'])) ? $_POST['statusID'] : 1;

三元运算符的格式为:$variable = condition ? if true : if false

它的美妙之处在于你将if / else语句缩短到一行,如果编译器给你错误,你总是可以回到那一行而不是3行。