PDO 获取数据返回字符串数组

问题描述 投票:0回答:1

我正在尝试使用

PDO
从 MySQL 数据库获取数据,但不幸的是
PDO
将结果作为字符串数组返回。我想在结果数组中保留本机 MySQL 数据类型。

我尝试将

PDO::ATTR_DEFAULT_FETCH_MODE
设置为
PDO::FETCH_ASSOC
PDO::FETCH_OBJ
但它仍然以字符串形式返回
INT
数据。

这是转储的结果:

array (size=1)
  0 => 
    object(stdClass)[27]
      public 'id' => string '3' (length=1)
      public 'avatar' => string '' (length=0)
      public 'fullName' => string 'Mikheil Janiashvili' (length=19)
      public 'email' => string '[email protected]' (length=17)
      public 'phone' => string '23 3537 20 03544' (length=12)
      public 'educationGE' => string '' (length=0)
      public 'educationEN' => string '' (length=0)
      public 'educationRU' => string '' (length=0)
      public 'experienceGE' => string '' (length=0)
      public 'experienceEN' => string '' (length=0)
      public 'experienceRU' => string '' (length=0)
      public 'descriptionGE' => string '' (length=0)
      public 'descriptionEN' => string '' (length=0)
      public 'descriptionRU' => string '' (length=0)
php mysql pdo
1个回答
7
投票

当您实例化 PDO 对象时,您需要告诉它使用 MySQL 的本机准备好的查询:

$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

假设您使用 PHP >= 5.3,您将使用 mysqlnd 库,它可以从准备好的查询中返回正确的数据类型。

示例:

$ php -a
Interactive shell

php > $db = PDO("mysql:host=localhost;dbname=test", "test", "");
php > $res = $db->query("SELECT 1 as num, PI()");
php > var_dump($res->fetch(PDO::FETCH_ASSOC));
array(2) {
  ["num"] => string(1) "1"
  ["PI()"] => string(8) "3.141593"
}

php > $db = PDO("mysql:host=localhost;dbname=test", "test", "", [PDO::ATTR_EMULATE_PREPARES=>false]);
php > $res = $db->query("SELECT 1 as num, PI()");
php > var_dump($res->fetch(PDO::FETCH_ASSOC));
array(2) {
  ["num"] => int(1)
  ["PI()"] => float(3.141593)
}
php > 
© www.soinside.com 2019 - 2024. All rights reserved.