Skip to content

Instantly share code, notes, and snippets.

@AeonFr
Last active August 16, 2019 12:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AeonFr/db3b2a8a95753076d9e4da42d29365d2 to your computer and use it in GitHub Desktop.
Save AeonFr/db3b2a8a95753076d9e4da42d29365d2 to your computer and use it in GitHub Desktop.
From a PDO Statement, fetch all the results and store them in an associative array, mapping integer and float values to PHP int and float types. It reads the column metadata to read the value's type.
<?php
// Returns the contents of $stm (PDO Statement)
// as an associative array, with correct native types
// for integers, nulls, and floats
$array = [];
while ($fila = $stm->fetch(\PDO::FETCH_ASSOC)) {
$i = 0;
$columnMetas = [];
while ($columnMeta = $stm->getColumnMeta($i)) {
$columnMetas[$columnMeta['name']] = $columnMeta;
$i++;
}
foreach ($fila as $key => $value) {
if ($value === null) {
continue;
}
$columnMeta = $columnMetas[$key];
switch ($columnMeta['native_type']) {
case 'LONG':
case 'TINY':
$fila[$key] = intval($value);
break;
case 'DOUBLE':
$fila[$key] = floatval($value);
break;
}
$i++;
}
$array[] = $fila;
}
return $array;
?>
@AeonFr
Copy link
Author

AeonFr commented Aug 16, 2019

Note: Tested in PHP 5.6 and MySQL 15.0 (10.0 MariaDB)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment