php PDO Fetch数据返回字符串数组

kd3sttzy  于 2023-10-15  发布在  PHP
关注(0)|答案(1)|浏览(135)

我试图用PDO从MySQL数据库中获取数据,但不幸的是,PDO返回的结果是一个字符串数组。我想在结果数组中保留原生MySQL数据类型。
我尝试将PDO::ATTR_DEFAULT_FETCH_MODE设置为PDO::FETCH_ASSOCPDO::FETCH_OBJ,但它仍然以字符串形式返回INT数据。
下面是dump的结果:

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)
vxbzzdmp

vxbzzdmp1#

当你示例化你的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 >

相关问题