Multiple Instances of Same parameter in PDO Statement


PDO is a good initiative by PHP to use instead of mysql_(…) functions. You can bypass a lot of security risks by using prepared statements. But it has a drawback as well which seems quite foolish to me.



When you write a SQL statement to be executed after prepareing it, you replace the actual values with what we call Parameters or Params.

$sql = “Select * from course where id=:courseId”;
$dbh->execute([‘:courseId’ => 1]);

In these statements, I am writing a sql statement to select all coulmns of table course where id is a param, then prepare it for execution and then pass the value of the actual parameter that needs to be replaced on run time. Upto this point, this all makes sense and works perfectly. Things change when you have more than one instances of same param and you expect the PDO to replace these all instances for you. like:

$sql = “Select * from course where id=:courseId or related_id=:courseId”
$dbh->execute([‘:courseId’ => 1]);

in this sql statements, you are trying to fetch all the rows where either id matches or related_id matches the ‘:courseId’ param which you will provide to PDO for execution. In this scenario, you will get an error:

“Invalid parameters number”

This is quite silly as you must be assuming PDO to replace all instances with provided param value, but it does not. For this statement to work, you need to replace second instance of ‘:courseId’ to some thing like ‘:courseId2’ or any other param and then providing value for that variable.

$sql = “Select * from course where id=:courseId or related_id=:courseId2”
$dbh->execute([‘:courseId’ => 1, ‘courseId2’ => 1]);

Quite surprising, but this is how they programmed it!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s