PHP: prepared statement, IF statement help needed

試著忘記壹切 提交于 2020-01-11 10:19:12

问题


I have the following code:

$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);

What I notice is the redundant multiple IF statements I have.

Question: is there any way to clean up my code so that I don't have these multiple IF statements for prepared statements?


回答1:


This is very similar to a question a user asked me recently the forum for my book SQL Antipatterns. I gave him an answer similar to this:

$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);



回答2:


Instead of if else just use PHP ternary operator

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

}

instead of that you can do:

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

The format of the ternary operator is: $variable = condition ? if true : if false

The beauty of it is that you will shorten your if/else statements down to one line and if compiler ever gives you errors, you can always go back to that line instead of 3 lines.



来源:https://stackoverflow.com/questions/2732734/php-prepared-statement-if-statement-help-needed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!