为什么PDO不允许多个同名占位符? [英] Why PDO doesn't allow multiple placeholders with the same name?

查看:82
本文介绍了为什么PDO不允许多个同名占位符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是PHP,而MySQL使用的是PDO.有时,我需要准备一个在此查询中多次使用一个变量(占位符)的语句.

I'm using PHP, and MySQL with PDO. Sometimes I need to prepare a statement with one variable (placeholder) used more than once in this query.

示例:

SELECT * FROM messages WHERE from_id = :user OR to_id = :user

但是,如果我尝试准备此语句,则会出现错误,因此我需要以如下方式进行操作:

However if I will try to prepare this statement I will have an error so I need to do this in a way like this:

SELECT * FROM messages WHERE from_id = :user1 OR to_id = :user2

要调用此语句,我将需要具有以下数组:

To call this statement I will need to have an array like this:

array('user1'=>$user_id, 'user2'=>$user_id);

对我来说真是太愚蠢了!为什么MySQL(PDO?)不允许我多次使用一个占位符,并迫使我使用需要更多控制权的额外变量?!

It looks so stupid for me! Why MySQL (PDO?) don't allowing me to use one place holder more than once and forcing me to use extra variables which requires more control?!

如果查询相对简单(如我在上面发布的内容),则可以轻松处理,但是现在我使用单个变量的5(!!!)个用法构建了一个查询.每次添加占位符时,都需要在许多地方检查代码以使其正常.

This can be handled easy if the query is relatively simple (like I posted above), but now I built a query with 5 (!!!) uses of single variable. Each time I add the placeholder I need to check the code in many places to make it OK.

是否有任何设置或调整项可以绕过此设置?

Is there any setting or a tweak to bypass this?

推荐答案

是否有任何设置或调整项可以绕过此设置?

Is there any setting or a tweak to bypass this?

是的,有. 您可以打开仿真模式,并可以多次使用相同的占位符.

Yes, there is. You can turn emulation mode ON and be able to use the same placeholder multiple times.

因此,仅当关闭仿真时,才会观察到所描述的行为.我真的不明白为什么会这样,但这是Wez Furlong(PDO作者)的解释:

So the described behavior is observed only when the emulation is turned OFF. I don't really understand why it is so but here is an explanation from Wez Furlong (the PDO author):

进行此更改有两个原因;首先,如果在绑定中重新使用相同的变量,则在使用某些驱动程序时可能会导致崩溃.无法保证做正确的事,有时可以使用触发崩溃的方法作为安全漏洞的攻击手段.

The change was made for two reasons; first and foremost, if you re-use the same variable in a bind, it is possible to induce a crash when using some drivers. It’s not possible to guarantee to do the right thing, and having a way to trigger a crash can sometimes be used as an attack vector for a security exploit.

第二个原因是可移植性.一些驱动程序会在内部执行此检查并输出错误.如果您针对不执行此操作的驱动程序进行编码,那么您的代码将不适用于未执行此操作的驱动程序.

The second reason is that of portability. Some drivers would internally perform this check and error out. If you code against the drivers that don’t enforce this, then your code won’t work on those that don’t.

http://paul-m-jones.com/archives/243# comment-740

这篇关于为什么PDO不允许多个同名占位符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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