简体   繁体   中英

Conditionally add WHERE statement to PDO query

I'm trying to conditionally search by date if such string is passed into my method, else no filter by date and all results will return. Pretty simple. I have the following code that is pretty gross, but is currently the only way that I can conceptualize how to add conditionally and still bindValue :

$qry = "SELECT orderid FROM ".$this->tableName."";
if ($filterFromDate) {
   error_log('----- has filter date');
   $qry .= " WHERE processed > :d";
}
$sth = $this->connection->prepare($qry);
if ($filterFromDate) {
   error_log('----- has filter date');
   $sth->bindValue(":d",$filterFromDate, \PDO::PARAM_STR);
}
$sth->execute();       
return $sth->fetchAll();

Is there a cleaner approach to this? Secondly, when no date filter is passed in, my query is failing - which can either be due to my gross approach or something deeper here.

As @Nigel Ren suggests, the way you could remove the if statement would be to maintain an array of parameters and then pass them into $sth->exec() . Something like this should work:

$params = [];
$qry = "SELECT orderid FROM ".$this->tableName."";
if ($filterFromDate) {
   error_log('----- has filter date');    
   $qry .= " WHERE processed > ?";
   $params[] = $filterFromDate;
}
$sth = $this->connection->prepare($qry);

$sth->execute($params);       
return $sth->fetchAll();

That said, this definitely counts a micro-optimization, so if you find it more readable, your original code is not bad.

Consider one single query that can handle a NULL parameter using COALESCE on a very early date.

// INITIALIZE AS NULL ENTITY
$filterFromDate = null; 
...

// RUN REGARDLESS OF VARIABLE STATE
$qry = "SELECT orderid FROM ".$this->tableName
       ."WHERE processed > COALESCE(:d, '1900-01-01')";

$sth = $this->connection->prepare($qry);
$sth->bindValue(":d", $filterFromDate, \PDO::PARAM_STR);
$sth->execute();       
return $sth->fetchAll();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM