Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

As I expand the data binding layer for my travelblog.ws project, I keep coming across different ways of breaking the PHP PDO statement class. The recent peculiarity that I've come across was to do with binding more variables than there were bind parameters in the SQL statement. In this situation, PDO will not return any data. In fact this is documented in the API...
Binding more values than specified is not possible; if more keys exist in input_parameters than in the SQL specified in the PDO::prepare(), then the statement will fail and an error is emitted.


Lets see the code that would cause the above behaviour. First there was some boiler plate code to write to execute a simple SQL statement (getting an ID from a 'posts' table for data that I know exists). There was a single bind parameter, ':id', in the SQL statement.
 PHP
$binds = ...; /* see specific examples below */
$sql = 'SELECT id FROM posts WHERE id = :id';
$statement = $dbConn->prepare($sql);
$results = $statement->execute($binds);
$data = $statement->fetchAll(\PDO::FETCH_OBJ);


when the $binds variable was set as follows:
 PHP
$binds = array('id' => '0f841cb12dc75');


I was getting data back as expected...
phpbindmany_2.png




However if I were to add some additional (non-sensical) bind parameter/value to the $binds array like this...
 PHP
$binds = array('id' => '0f841cb12dc75', 'a' => 'b');


Instead of ignoring the bind parameter that does not appear in the SQL statement, PDO instead returned no data.
phpbindmany_1.png


Additionally the following warning was emitted to the PHP error log:
 Error
PHP Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in dbtest.php on line 33


The above all made sense, though I was half-expecting that PDO would simply ignore any extra bind parameters.

-i

A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.