0

Is there a way to allow the number of parameters passed thru PDO::Execute to be greater than the number of tokens identified in the prepare statement?

For example:

$john = Array("name"=>"John", "lastname"=>"Smith","occupation"=>"Citizen");

$pdo = $db->prepare("SELECT * FROM Users WHERE name = :name AND lname = :lastname");

$result = $pdo->execute($john);

In this example, PDO would throw a warning:

Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[HY093]:
Invalid parameter number:
number of bound variables does not match number of tokens in...

Can PDO be set to simply ignore additional parameters that don't have a matching token name?

Moe
  • 4,744
  • 7
  • 28
  • 37
  • 1
    Why do you even have `Citizen` in your array if you don't need it? – Rizier123 Aug 18 '15 at 23:00
  • If you look into the manual: http://php.net/manual/en/pdostatement.execute.php You will see in the changelog, that it silently failed prior PHP 5.2 – Rizier123 Aug 18 '15 at 23:04
  • @Rizier123 - This is just an example, my actually Array has around 10 different name keys - I'm taking the 'lazy' route rather than having to redefine an array with the specific values in each execute. – Moe Aug 18 '15 at 23:11
  • Thanks @Rizier123 - That link did actually help. Shame that PDO isn't smart enough to simply disregard the tokens that aren't in the prepare statement. – Moe Aug 19 '15 at 05:46
  • On the contrary, it might be assuming that you as the developer have done something wrong when the supplied params don't match the prepared statement, maybe PDO is doing you a favour to prevent unwanted side effects? – scrowler Aug 19 '15 at 22:26

1 Answers1

0

I am assuming you cannot turn this error off but how about this for a work around

If you catch the error, check its this specific error and if it is ignore it, would that work?

So something like this :

try {
    $john = Array("name"=>"John",
                  "lastname"=>"Smith",
                  "occupation"=>"Citizen"
                 );

    $pdo = $db->prepare("SELECT * 
                         FROM Users 
                         WHERE name = :name 
                           AND lname = :lastname"
                       );

    $result = $pdo->execute($john);
}
catch (PDOException $e) {
    if ( $e->getCode() !== 'HY093' ) {
        // report error like normal
        exit;
    }
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149