为什么 PDO_MySQL 不返回整数?

2021-12-26 00:00:00 php mysql pdo

我正在将我的 PHP 代码从 mysql(在 5.5 中弃用)迁移到 PDO_MySQL.但是,mysql_fetch_row 返回整数,而 PDOStatement::fetch 返回数字字符串.我怎样才能让 PDO 表现得像前者一样?

I'm migrating my PHP codes from mysql (deprecated in 5.5) to PDO_MySQL. However, mysql_fetch_row returns integer while PDOStatement::fetch returns strings for numbers. How can I make PDO behaves like the former one?

mysql_fetch_row 的结果:

array(1) {
  ["id"]=>
  int(1)
}

PDOStatement::fetch 的结果:

array(1) {
  ["id"]=>
  string(1) "1"
}

推荐答案

PDO::ATTR_EMULATE_PREPARES 设置为 false,如果您确实需要使用松散类型的 PHP

Set PDO::ATTR_EMULATE_PREPARES to false, if you really need it with loosely-typed PHP

如果 mysql_fetch_row 为 SUM 返回 int 或者(我从不关心检查) - 那么它会做一些魔术,比如 if (ctype_digit($val)) $row[$key] =(int)$val; - 所以你可以在你的 DBAL 中做

If mysql_fetch_row returns you int for SUM either (I never cared to check) - then it does some magic like if (ctype_digit($val)) $row[$key] = (int)$val; - so you can do in your DBAL

据我了解准备语句的工作方式,它使用相同的数据包结构来发送和检索数据,并且该数据包包含数据类型.

As far as I understand the way prepared statements works, it uses the same packet structure for either sending and retrieving data, and this packet contains data type.

看起来那个服务器可以返回两种格式的数据——native 和 mysqlnd,这取决于请求类型.后一个可以被客户端库解释为转换结果值.

It looks like that server can return data in 2 formats - native and mysqlnd, depends on the request type. A latter one can be interpreted by client library to cast resulting value.

相关文章