PHP: prepared statement, IF statement required

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 few IF statements that I have.

Question : is there a way to clear my code so that I don't have these few IF statements for prepared statements?

+2
source share
2 answers

This is very similar to a user question asked me recently in the forum for my SQL Antipatterns book. 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
source

Instead of if else, just use the PHP ternary operator

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

}

instead you can:

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

Ternary Operator Format: $variable = condition ? if true : if false

, if/else , - , .

+1

Source: https://habr.com/ru/post/1744418/


All Articles