Vlada Katlinskaya Vlada Katlinskaya - 1 year ago 80
MySQL Question

PHP's PDO prepared statement: am I able to use one placeholder multiple times?

I'd like to perform the following query:

(SELECT COUNT(*) FROM `tab2` WHERE `parent` = :id) AS `sum`
FROM `tab1`
WHERE `id` = :id

As you can see
placeholder appeared twice in the query. So if I'd try to execute this statement with:


I'm receiving the error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number

So I have to rewrite the prepared query and execute array with :id1 and :id2 placeholders which looks a bit stupid for me.

Is it the only way to use one placeholder in several places of the prepared statement?

Answer Source

PDO::prepare states that

[y]ou cannot use a named parameter marker of the same name more than once in a prepared statement, unless emulation mode is on.

Since it's generally better to leave emulation mode off (so the database does the prepared statement), you'll have to use id_0, id_1, etc.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download