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

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

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程