如何使用PDO插入NULL值? [英] How do I insert NULL values using PDO?

查看:98
本文介绍了如何使用PDO插入NULL值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码,但我感到无比沮丧:

I'm using this code and I'm beyond frustration:

try {
    $dbh = new PDO('mysql:dbname=' . DB . ';host=' . HOST, USER, PASS);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbh->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
}
catch(PDOException $e)
{
    ...
}
$stmt = $dbh->prepare('INSERT INTO table(v1, v2, ...) VALUES(:v1, :v2, ...)');
$stmt->bindParam(':v1', PDO::PARAM_NULL); // --> Here's the problem

PDO::PARAM_NULL, null, '',所有人都失败并抛出此错误:

PDO::PARAM_NULL, null, '', all of them fail and throw this error:

致命错误:无法在/opt/...中通过引用传递参数2.

Fatal error: Cannot pass parameter 2 by reference in /opt/...

推荐答案

我只是在学习PDO,但我认为您需要使用bindValue,而不是bindParam

I'm just learning PDO, but I think you need to use bindValue, not bindParam

bindParam接受一个变量以进行引用,并且在调用bindParam时不提取值.我在对php文档的评论中发现了这一点:

bindParam takes a variable, to reference, and doesn't pull in a value at the time of calling bindParam. I found this in a comment on the php docs:

bindValue(':param', null, PDO::PARAM_INT);

PS您可能会想这样做bindValue(':param', null, PDO::PARAM_NULL);,但是它并不适合所有人(感谢您将Shaver进行举报).

P.S. You may be tempted to do this bindValue(':param', null, PDO::PARAM_NULL); but it did not work for everybody (thank you Will Shaver for reporting.)

这篇关于如何使用PDO插入NULL值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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