1

如果我的数据库中有 NULL 值并将它们拉到一个数组中,我会得到空字符串。例如:

$test = [];
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
    $test[$row['id']]['field1'] = $row['field1'];
    $test[$row['id']]['field2'] = $row['field2']; // null in database
    $test[$row['id']]['field3'] = null; // explicitly set to null
}
return $test;

输出:

array(1) {
  [1]=>
  array(3) {
    ["field1"]=>
    string(4) "test"
    ["field2"]=>
    string(0) ""
    ["field3"]=>
    string(0) ""
  }
}

我只是想了解为什么我最终得到的是空字符串而不是 NULL 值?我做错了什么还是它应该工作的方式?

4

2 回答 2

1

PDO 不会自动检索本机 MySQL 数据类型。为此,您必须使用准备好的语句并且必须运行 PHP 5.3(前提是您的 PHP 5.3 版本是使用 mysqlnd(而不是旧的 libmysql)编译的)。

此外,您必须像这样建立连接:

$conn = new PDO($dsn, $user, $pass, array(
    PDO::ATTR_EMULATE_PREPARES => false
));

PDO::ATTR_EMULATE_PREPARES 启用或禁用准备好的语句的模拟。

来源: http: //php.net/manual/en/pdo.setattribute.php

为了查看实际的 NULL 值,您需要执行var_dump或通过使用检查该值是否为空is_null

于 2013-08-24T21:07:28.450 回答
1

尝试这个:

$db->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_NATURAL );

PDO::NULL_NATURAL: 没有转换。

于 2013-08-24T21:52:20.293 回答