PHP: prepared statement, IF statement help needed

Posted by JGreig on Stack Overflow See other posts from Stack Overflow or by JGreig
Published on 2010-04-28T20:02:46Z Indexed on 2010/04/28 20:07 UTC
Read the original article Hit count: 219

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?

© Stack Overflow or respective owner

Related posts about php

Related posts about programming-languages