PDO Fetch returns an array of strings

I am trying to get data from a MySQL database using PDO, but, unfortunately, PDOreturns the result as an array of strings. I want to store my own MySQL data types in an array of results.

I tried to set PDO::ATTR_DEFAULT_FETCH_MODEas PDO::FETCH_ASSOCAND PDO::FETCH_OBJ, but still returned the data INTas a string.

Here is the dump result:

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 'xxxxx@yyyyy.com' (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)
+4
source share
1 answer

When you instantiate the PDO, you need to tell it to use prepared MySQL queries:

$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, PI()");
php > var_dump($res->fetch());
array(4) {
  [1]=>
  string(1) "1"
  [2]=>
  string(1) "1"
  ["PI()"]=>
  string(8) "3.141593"
  [3]=>
  string(8) "3.141593"
}

php > $db = PDO("mysql:host=localhost;dbname=test", "test", "", [PDO::ATTR_EMULATE_PREPARES=>false]);
php > $res = $db->query("SELECT 1, PI()");
php > var_dump($res->fetch());
array(4) {
  [1]=>
  int(1)
  [2]=>
  int(1)
  ["PI()"]=>
  float(3.1415926535898)
  [3]=>
  float(3.1415926535898)
}
php > 
+2

Source: https://habr.com/ru/post/1621122/


All Articles