doucai9270 2017-09-17 18:50
浏览 78
已采纳

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

I use a lot of sql statements using PostgreSQL and PHP and many of them have variables in the 'WHERE' clause. 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. 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. 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:

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

1条回答 默认 最新

  • doujiong2533 2017-09-17 18:55
    关注

    As you can see on this link you the PDO's execute method returns boolean by definition.

    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. 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里