且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 PHP 中将整数和数字列从 MySQL 返回为整数和数字?

更新时间:2023-08-31 14:32:22

解决方案是确保您使用的是 mysqlnd php 驱动程序.

The solution is to ensure that you are using the mysqlnd driver for php.

查看php -i 时,不会 提到mysqlnd".pdo_mysql 部分将包含如下内容:

When viewing php -i, there will be no mention of "mysqlnd". The pdo_mysql section will have something like this:

pdo_mysql

PDO Driver for MySQL => enabled Client API version => 5.1.72

你如何安装它?

大多数 L/A/M/P 安装指南都建议 apt-get install php5-mysql 但 MySQL 的本机驱动程序由不同的包安装:php5-mysqlnd代码>.我发现这在 ppa:ondrej/php5-oldstable 中可用.

How do you install it?

Most installation guides for L/A/M/P suggest apt-get install php5-mysql but the native driver for MySQL is installed by a different package: php5-mysqlnd. I found that this was available with the ppa:ondrej/php5-oldstable.

要切换到新驱动程序(在 Ubuntu 上):

To switch to the new driver (on Ubuntu):

  • 删除旧驱动程序:
    apt-get 删除 php5-mysql
  • 安装新驱动程序:
    apt-get install php5-mysqlnd
  • 重启apache2:
    服务apache2重启

现在 php -i 将在 pdo_mysql 部分明确提及mysqlnd":

Now php -i will mention "mysqlnd" explicitly in the pdo_mysql section:

pdo_mysql

PDO Driver for MySQL => enabled
Client API version => mysqlnd 5.0.10 - 20111026 - $Id:      e707c415db32080b3752b232487a435ee0372157 $

PDO 设置

确保 PDO::ATTR_EMULATE_PREPARESfalse(检查您的默认值或设置它):
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

PDO settings

Ensure that PDO::ATTR_EMULATE_PREPARES is false (check your defaults or set it):
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

确保 PDO::ATTR_STRINGIFY_FETCHESfalse(检查您的默认值或设置它):
$pdo->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);

Ensure that PDO::ATTR_STRINGIFY_FETCHES is false (check your defaults or set it):
$pdo->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);

  • 浮点类型(FLOAT、DOUBLE)作为 PHP 浮点数返回.
  • 整数类型(INTEGER、INT、SMALLINT、TINYINT、MEDIUMINT、BIGINT †)作为 PHP 整数返回.
  • 定点类型(DECIMAL、NUMERIC)作为字符串返回.

† 值大于 64 位有符号整数 (9223372036854775807) 的 BIGINT 将作为字符串返回(或 32 位系统上的 32 位)

† BIGINTs with a value greater than a 64 bit signed int (9223372036854775807) will return as a string (or 32 bits on a 32 bit system)

    object(stdClass)[915]
      public 'integer_col' => int 1
      public 'double_col' => float 1.55
      public 'float_col' => float 1.5
      public 'decimal_col' => string '1.20' (length=4)
      public 'bigint_col' => string '18446744073709551615' (length=20)