PHP的PDO准备声明:我可以多次使用一个占位符吗? [英] PHP's PDO prepared statement: am I able to use one placeholder multiple times?

查看:91
本文介绍了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?

推荐答案

PDO :: prepare 指出

[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_0id_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.

这篇关于PHP的PDO准备声明:我可以多次使用一个占位符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆