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);