jeudi 28 avril 2016

Optional section in bound PDO query

I have the following code:

$sql = "SELECT * FROM image WHERE id >= :from";
$bind = array(":from" => $from);
if(isset($to)) {
    $sql .= " AND id <= :to";
    $bind[":to"] = $to;
}
$request = $database->prepare($sql);
$request->execute($bind);
print_r($request->fetchAll());

This feels pretty unclean, but it works. What I want to find out is if there is a cleaner way of having an optional piece of SQL and an optional bound variable without triggering exceptions (as occurred when I tried placing both the binds at the end and leaving one NULL).

Is there an alternative way to write this code?

Aucun commentaire:

Enregistrer un commentaire