简体   繁体   English

有条件地将 WHERE 语句添加到 PDO 查询

[英]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 :我有以下非常粗略的代码,但目前是我可以概念化如何有条件地添加并且仍然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() .正如@Nigel Ren建议的那样,删除if语句的方法是维护一个参数数组,然后将它们传递给$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.考虑一个可以在很早的日期使用COALESCE处理NULL参数的查询。

// 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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