[英]PDO select all data from table with “where” clause
I want to pass $variable parameter to php function and according to this parameter get data from table. 我想将$ variable参数传递给php函数,并根据此参数从表中获取数据。 This parameter can be null, which means that db request should take all data from the table or it can be int value. 此参数可以为null,这意味着db request应该从表中获取所有数据,也可以为int值。 Here is the code I try: 这是我尝试的代码:
$stmt = $this->_db->prepare("SELECT * FROM ki_cities
WHERE id IS NULL OR id = :user");
$stmt->bindValue(':user',$variable,PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
This query doesn't return any row. 该查询不返回任何行。
Here is implicit question for those who are confused by my question. 对于那些对我的问题感到困惑的人来说,这是一个隐含的问题。 I want sql query: 我想要SQL查询:
SELECT * FROM ki_cities WHERE id = *
this query should do the same as: 此查询应与以下操作相同:
SELECT * FROM ki_cities
I suppose my question is clear. 我想我的问题很清楚。
======================================= =======================================
Here is my twisted "solution" if someone interested: 如果有人感兴趣,这是我扭曲的“解决方案”:
$que = "SELECT * FROM ";
$que = $que . " ki_students where season=4";
if($type!=null) { $que = $que . " and type =".$type; }
if($city!=null) { $que = $que . " and city =".$city; }
$stmt = $this->_db->prepare($que);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
If I understand your "question" right, the code can be: 如果我理解您的“问题”正确,则代码可以是:
$stmt = $this->_db->prepare('SELECT * FROM `ki_cities` WHERE ((:user IS NULL) OR (`id` = :user));');
$stmt->bindValue(':user', $variable, is_null($variable) ? PDO::PARAM_NULL : PDO::PARAM_INT);
(or you can omit argument #3 to bindValue() and let PDO autodetect data type) (或者您可以将参数#3省略为bindValue()并让PDO自动检测数据类型)
There are 2 possible cases here: 这里有2种可能的情况:
The statement does not return any rows as it makes very little sense. 该语句不返回任何行,因为它意义不大。
Maybe this would be a better way of thinking about that situation 也许这是思考这种情况的更好方法
if ( empty($variable) ) {
$stmt = $this->_db->prepare("SELECT * FROM ki_cities");
} else {
$stmt = $this->_db->prepare("SELECT * FROM ki_cities WHERE id = :user");
$stmt->bindValue(':user',$variable,PDO::PARAM_INT);
}
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
For prepared statements you always have to generate them in a "literal" way, so that does not let you avoid the process which RiggsFolly describes. 对于准备好的语句,您始终必须以“文字”方式生成它们,因此不能避免您使用RiggsFolly描述的过程。 If you want an "optimal" solution you can ask if a variable is null in other ways. 如果需要“最佳”解决方案,则可以通过其他方式询问变量是否为null。 Eg: as this thread explains. 例如:如该线程所解释。
Hope it helps you 希望对您有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.