php – 为什么PDO :: ATTR_EMULATE_PREPARES => TRUE将所有值作为字符串返回

使用不同版本的php和
mysql,通过使用本机预处理语句或模拟预处理语句,有可能是否具有natine值类型,如下所示:

$value = $db->query("SELECT 1033 AS Code")->fetch(PDO::FETCH_COLUMN)
$value2 = $db->query("SELECT '1033' AS Code")->fetch(PDO::FETCH_COLUMN);

//PDO::ATTR_EMULATE_PREPARES set to true:
var_dump($value); // string(4) "1033"
var_dump($value2); // string(4) "1033"

//PDO::ATTR_EMULATE_PREPARES set to false:
var_dump($value); // int(1033)
var_dump($value2); // string(4) "1033"

this文章:

The problem is that PDO causes a zval-separation due to a type cast to string. The cast is requested by the PDO core.

PDO will always cast data to string by default and the PDO_MYSQL driver can only work around this PDO default by returning zvals.

为什么PDO总会将数据转换为字符串?

最佳答案
Provided that

PDO will emulate prepared statements/bound parameters for drivers that do not natively support them

…此功能(模拟预处理语句)可能由一段代码处理,这些代码对所有驱动程序都是通用的.

但是,基于PDOStatement::getColumnMeta()等功能未针对所有驱动程序实现的事实,

Not all PDO drivers support PDOStatement::getColumnMeta().

…我假设PDO公共代码库无法以一致的跨数据库方式确定数据库列类型,因此必须回退到通用字符串类型.

不幸的是,源代码对我来说太过模糊,无法验证这些假设.

点赞