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

与世无争的帅哥 提交于 2019-11-27 07:33:02

问题


This question already has an answer here:

  • PDO Parameterized Query - Reuse named placeholders? 4 answers

I'd like to perform the following query:

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

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

$q->execute(['id'=>$row_id]);

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?


回答1:


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.



来源:https://stackoverflow.com/questions/27461763/phps-pdo-prepared-statement-am-i-able-to-use-one-placeholder-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!