PDO 参数化查询 - 重用命名占位符?
本质上,我有一个必须在 SQL 查询中调用几次的值。因此,是否可以在语句中重用相同的命名占位符,例如 SELECT :Param FROM Table WHERE Column = :Param
,然后简单地bindValue(":Param"),并让两个:Params 都有值?
In essence, I have a value that I have to call a couple times in my SQL query. Thus, is it possible to reuse the same named placeholder in the statement e.g.SELECT :Param FROM Table WHERE Column = :Param
, then simply bindValue(":Param"), and have the value be there for both :Params?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
PDO::prepare 声明“您不能使用相同的命名参数标记在准备好的声明中命名两次”,所以我想那是不行的。
PDO::prepare states that "you cannot use a named parameter marker of the same name twice in a prepared statement", so I guess that's a no then.
如果您设置
PDO::ATTR_EMULATE_PREPARES = true
,则可以。例如
$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
。如果您使用 Laravel,您可以在
config/database.php
的options
数组中进行设置。例如PDO::ATTR_EMULATE_PREPARES =>正确
You can if you set
PDO::ATTR_EMULATE_PREPARES = true
.E.g.
$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
.If you're using Laravel you can set this in an
options
array inconfig/database.php
. e.g.PDO::ATTR_EMULATE_PREPARES => true
除了重用之外,这里的主要问题是您试图动态更改列名称。
此答案由匿名用户在 http://php.net/manual/en/pdo 上发布.prepare.php:
当您的查询使用动态列引用时,您应该将已知存在于表中的列显式列入白名单,例如使用 switch 语句并在 default: 子句中抛出异常。
Apart from reuse, the main issue here is that you are trying to dynamically change col names.
This answer posted by an anonymous user on http://php.net/manual/en/pdo.prepare.php :
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.
许多像您这样的查询可以重写为仅使用一个占位符。
会是一样的
但有时没那么简单。例如:
在这种情况下,您可以重用将其存储在交叉连接派生表中的参数值(FROM 子句中的子查询):
Many queries like yours can be rewritten to use only one placeholder.
would be the same as
But sometimes it's not that simple. For example:
In such case you could reuse the parameter value storing it in a cross joined derived table (subquery in FROM clause):
正如其他人指出的那样,有很多解决方法:
ATTR_EMULATE_PREPARES
设置为true
如果上述方法不可能也不可取,还有另一种优雅的方法可以解决此问题,即在 SQL 中使用变量:
然后通过分配 <代码>值。
As others pointed out, there are quite some workarounds:
ATTR_EMULATE_PREPARES
totrue
If the above is not possible nor desirable, there is another elegant way to solve this, by using variables in SQL:
Then prepare this statement by just assigning
value
.有一个解决方法:
总之,使用具有相同条件的不同占位符。
There's a workaround:
In summary, use different placeholders with the same criteria.