PDO令牌需要匹配bindValue 1:1吗? [英] Do PDO tokens need to match the bindValue 1:1?

查看:38
本文介绍了PDO令牌需要匹配bindValue 1:1吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码

$query = 'INSERT INTO table
                  (foo, bar, baz)
                  VALUES
                  (:foo, :bar, :baz)
          ON DUPLICATE KEY UPDATE foo = :foo,
                                  bar = :bar,
                                  baz = :baz';
$stmt = $dbc->prepare($query);
$stmt->bindValue(':foo', $foo, PDO::PARAM_STR);
$stmt->bindValue(':bar', $bar, PDO::PARAM_STR);
$stmt->bindValue(':baz', $baz, PDO::PARAM_STR);

$stmt->execute();

它抛出一个错误:

致命错误:消息'SQLSTATE [HY093]:未捕获的异常'PDOException':无效的参数编号:绑定变量的数量与令牌数量不符

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

很明显,令牌的数量是绑定变量的两倍,但是唯一令牌的数量却相同.所以我的问题是,每个令牌只能使用一次吗?我是否需要重命名每个令牌的第二个实例才能使其正常工作,或者有一种方法可以在不使我的bindValue语句加倍的情况下进行操作?

Obviously, I have twice as many token as bound variables, but I have the same number of unique tokens. So my question is, can each token only be used once? Will I need to rename the second instance of each token to get it to work, or is there a way to do it without doubling my bindValue statements?

推荐答案

事实证明,您可以重用令牌.我的错误完全是另外一回事.因此,如果您将来发现这个问题并想知道同一件事,是可能的.您的错误是由其他原因引起的.可能错过了冒号或您的令牌混乱,忘记为其中一个添加bindValue.

It turns out that you can reuse tokens. My error was something else entirely. So if you find this in the future wondering the same thing, yes it's possible. Your error is from something else. Probably missed a colon or in your mess of tokens forgot to add a bindValue for one.

如下面的Barmar所述,此功能可能需要 PDO::ATTR_EMULATE_PREPARES 使发生. MySQL默认情况下启用了该功能,但是如果使用Laravel之类的框架,则可能将其关闭.

As noted by Barmar below, this functionality may need PDO::ATTR_EMULATE_PREPARES enabled to occur. MySQL has it enabled by default, though if using a framework such as Laravel, it may be turned off.

此答案包含有关如何启用Laravel的说明.

这篇关于PDO令牌需要匹配bindValue 1:1吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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