Furze Furze - 7 months ago 9
PHP Question

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?

Answer

If you really want a cleaner code like this,

$qb = DB::table('image')->where('id', '>=', $from);
if(isset($to)) {
    $qb->andWhere('id', '<=', $to)
}
$data = $qb->get()

you have to look towards Query Builders

While for the raw PDO your code is the best you can get.

Comments