PHP PDO -为什么我的fetchAll()在使用json_encode时将所有值转换为字符串?

kx1ctssn  于 2023-04-04  发布在  PHP
关注(0)|答案(3)|浏览(140)

我在一个表上做了一个select all SQL查询,并在PHP中的一个准备好的查询中运行它。然后我在json_encode中回显结果。结果是将每个值都作为字符串,甚至行ID也是INT。你如何保持原始的值类型?

$sql = "SELECT * FROM `Type`";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($result);

输出如下所示:

[{"ID":"1","Type":"Classic Starters","Description":""},{"ID":"2","Type":"Special Starters","Description":""}]

所需输出如下:

[{"ID":1,"Type":"Classic Starters","Description":""},{"ID":2,"Type":"Special Starters","Description":""}]

提前感谢〈3

dced5bon

dced5bon1#

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

这解决了我的问题

cetgtptt

cetgtptt2#

我在使用Doctrine时也遇到了同样的问题,所以基本上解决方法是PDO,特别是如果您不想或无法配置它以避免转换为字符串的话。
创建一个类

Class Entity {
    public int $ID;
    public string $Type;
    public string $Description;
}

然后将类名与\PDO::FETCH_CLASS沿着传递

$sql = "SELECT * FROM `Type`";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(\PDO::FETCH_CLASS, Entity::class);

$result将是这样的:

array:2 [
  0 => Entity {
    ID: 1
    Type: "Classic Starters"
    Description: ""
  }
  1 => Entity {
    ID: 1
    Type: "Special Starters"
    Description: ""    
  }
]
gz5pxeao

gz5pxeao3#

我需要使用一个 “动态类名”。所以这里有一个替代@Sergey Onishchenko的答案:

//I conditionally set the class name and sql statement.
$fetchClass='Entity';
$sql = "SELECT * FROM `Type`";

$stmt = $pdo->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_CLASS, $fetchClass); //I removed the backslash in front of PDO::FETCH_CLASS, because I don't know it's purpose and it also works wihout a backlash.

它不使用Entity::class或变量名,而是直接使用字符串:

$result = $stmt->fetchAll(PDO::FETCH_CLASS, 'Entity');

相关问题