0

I'm trying to get native types out of a database query using PostgreSQL (v. 14) via PHP PDO.

Despite using PDO::ATTR_STRINGIFY_FETCHES => false, the result comes out as a string, e.g. "1.2" rather than 1.2. Here's a reproduce case:

<?php

$pdo = new PDO ("pgsql:host=localhost;dbname=database", 'username', 'password', array (
    PDO::ATTR_EMULATE_PREPARES => false,
    PDO::ATTR_STRINGIFY_FETCHES => false
));

$query = "DROP TABLE IF EXISTS floattest;";
$pdo->exec ($query);

$query = "CREATE TABLE floattest (id FLOAT);";
$pdo->exec ($query);

$query = "INSERT INTO floattest VALUES (1.2);";
$pdo->exec ($query);

$query = 'SELECT * FROM floattest;';
$statement = $pdo->prepare ($query);
$statement->execute ();
$data = $statement->fetchAll (PDO::FETCH_ASSOC);

var_dump ($data[0]['id']);

// Expected value is 1.2 but what is returned is "1.2"

?>

Is this a bug, or am I doing something wrong?

fooquency
  • 1,575
  • 3
  • 16
  • 29

1 Answers1

0

Until PHP 5.2 Postgre PDO returns strings even when the column is numeric, or datetime. You need to convert them implicitly:

$floatReturn = floatval($data[0]['id']);

From PHP 5.3 there are other solutions.
See How to get numeric types from MySQL using PDO?

  • Is this documented anywhere, that Postgres PDO doesn't return the correct types? There are references around the web suggesting it does. – fooquency Feb 21 '22 at 10:54