简体   繁体   English

无法将参数绑定到WHERE子句PDO

[英]Can't bind parameters to WHERE clause PDO

I use a lot of sql statements using PostgreSQL and PHP and many of them have variables in the 'WHERE' clause. 我使用PostgreSQL和PHP使用了很多sql语句,其中很多都在'WHERE'子句中有变量。 I can get prepared statements to execute just fine for INSERT and UPDATE but I can't make it work for SELECT statements with variables in the WHERE clause. 我可以获得准备好的语句来执行INSERT和UPDATE,但是我不能使它适用于WHERE子句中带变量的SELECT语句。 I have scoured google for an answer with no success. 我已经搜索谷歌的答案没有成功。 Please take a look at the example below. 请看下面的例子。 This is to select a recent reconciled bank balance from a table called bankrec. 这是从名为bankrec的表中选择最近的对帐银行余额。 What am I missing? 我错过了什么?

$rec = $dbh->prepare('SELECT clearedbal FROM bankrec WHERE bankno = :bankno ');
$result = $rec->execute(['bankno'=>$bankno])->fetch(PDO::FETCH_ASSOC);

When I run this I get: 当我运行这个时,我得到:

"Fatal error: Call to a member function fetch() on boolean"

However, I know the query is correct because simply running a query without a prepared statement gets me the result I want, but it is vulnerable to sql injection: 但是,我知道查询是正确的,因为只是在没有预准备语句的情况下运行查询会得到我想要的结果,但它很容易受到sql注入:

$rec = $dbh->query("SELECT clearedbal FROM bankrec WHERE bankno = '$bankno' ")->fetch(PDO::FETCH_ASSOC);

As you can see on this link you the PDO's execute method returns boolean by definition. 正如您在链接中看到的那样,PDO的execute方法按定义返回boolean。

I would recommend this approach: 我会推荐这种方法:

$rec = $dbh->prepare('SELECT clearedbal FROM bankrec WHERE bankno = :bankno ');
if($rec->execute(['bankno'=>$bankno])){
  $result=$rec->fetch(PDO::FETCH_ASSOC);
  //do another stuff there
} else {
  //Query failed handle error
}

As you can see you can use the execute in order to determine if query sucessfully executed or not. 如您所见,您可以使用execute来确定查询是否成功执行。 Also if you need to fetch more than one line of result you should use the fetchAll method: http://php.net/manual/en/pdostatement.fetchall.php 此外,如果您需要获取多行结果,则应使用fetchAll方法: http//php.net/manual/en/pdostatement.fetchall.php

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

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