微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 为什么模拟准备好的语句失败?

PHP manual开始,它声明:

PDO::ATTR_EMULATE_PREPARES Enables or disables emulation of prepared
statements. Some drivers do not support native prepared statements or
have limited support for them. Use this setting to force PDO to either
always emulate prepared statements (if TRUE), or to try to use native
prepared statements (if FALSE). It will always fall back to emulating
the prepared statement if the driver cannot successfully prepare the
current query. Requires bool.

我有一个像这样的查询

$type = PDO::ParaM_INT;
if($_POST['code'] == "") $type = PDO::ParaM_NULL;

$stmt = $dbh->prepare("UPDATE Product SET code=? WHERE id=?");
$stmt->bindValue(1, $_POST['code'], $type);
$stmt->bindValue(2, $_SESSION['id'], PDO::ParaM_INT);
$stmt->execute();

我意识到,如果不设置以下语句,我将使用上面的代码在我的数据库中获得一个’0’而不是NULL值(当$_POST [‘code’] ==“”时).为什么会这样?

$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

更新:

虽然禁用仿真对我有用,但我更喜欢使用它,因为就像这个question中的OP一样,基本上我的所有查询只在每个脚本执行时执行一次.因此,准备好语句不会给我带来任何好处,并且会创建对数据库的不必要调用,如下面的常规查询日志中所示:

Emulation disabled
22 Connect user@localhost on Database
22 Prepare UPDATE Product SET code=? WHERE id=?
22 Execute UPDATE Product SET code='abc' WHERE id='123'
22 Close stmt   
22 Quit

Emulation Enabled
22 Connect user@localhost on Database
22 Query UPDATE Product SET code='abc' WHERE id='123'
22 Quit

任何帮助解决NULL问题非常感谢.

解决方法:

尝试为PDO :: ParaM_NULL绑定null.

$type = PDO::ParaM_INT;
if($_POST['code'] == "") {
    $_POST['code'] = null;
    $type = PDO::ParaM_NULL;
}

$stmt = $dbh->prepare("UPDATE Product SET code=? WHERE id=?");
$stmt->bindValue(1, $_POST['code'], $type);
$stmt->bindValue(2, $_SESSION['id'], PDO::ParaM_INT);
$stmt->execute();

实际上,似乎你不需要使用PDO :: ParaM_NULL,下面的代码也会插入null.

$stmt->bindValue(1, $_POST['code'] ? $_POST['code'] : null, PDO::ParaM_INT);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐