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