note 111976 deleted from pdo.prepare by aharvey
| From: | aharvey@php.net | Date: | Thu, 18 Apr 2013 17:43:44 +0000 |
| Subject: | note 111976 deleted from pdo.prepare by aharvey | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-194539@lists.php.net to get a copy of this message | ||
Note Submitter: rowan dot collins at cwtdigital dot com
----
To those wondering why adding quotes to around a placeholder is wrong, and why you can't use
placeholders for table or column names:
There is a common misconception about how the placeholders in prepared statements work: they are not
simply substituted in as (escaped) strings, and the resulting SQL executed. Instead, a DBMS asked to
"prepare" a statement comes up with a complete query plan for how it would execute that
query, including which tables and indexes it would use, which will be the same regardless of how you
fill in the placeholders.
The plan for "SELECT name FROM my_table WHERE id = :value" will be the same whatever you
substitute for ":value", but the seemingly similar "SELECT name FROM :table WHERE id
= :value" cannot be planned, because the DBMS has no idea what table you're actually going
to select from.
Even when using "emulated prepares", PDO cannot let you use placeholders anywhere, because
it would have to work out what you meant: does "Select :foo From some_table" mean
":foo" is going to be a column reference, or a literal string?
When your query is using a dynamic column reference, you should be explicitly white-listing the
columns you know to exist on the table, e.g. using a switch statement with an exception thrown in
the default: clause.