PHP的PDO准备声明:我可以多次使用一个占位符吗?
我想执行以下查询:
SELECT
*,
(SELECT COUNT(*) FROM `tab2` WHERE `parent` = :id) AS `sum`
FROM `tab1`
WHERE `id` = :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]);
我收到错误消息:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number
所以我必须重写准备好的查询并使用:id1和:id2占位符执行数组,这对我来说有点愚蠢.
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?
[y] ou不能在准备好的语句中多次使用相同名称的命名参数标记,除非启用了仿真模式.
[y]ou cannot use a named parameter marker of the same name more than once in a prepared statement, unless emulation mode is on.
由于通常最好关闭仿真模式(因此数据库执行准备好的语句),因此您必须使用id_0
,id_1
等.
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.