Created
January 16, 2013 09:13
-
-
Save oscar-broman/4545758 to your computer and use it in GitHub Desktop.
Fetch MySQLi results properly typed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function mysqli_fetch_all_typed($result, $resulttype = MYSQLI_NUM) | |
{ | |
if (!$result) | |
return null; | |
$fields = $result->fetch_fields(); | |
if (method_exists($result, 'fetch_all')) { | |
$rows = $result->fetch_all($resulttype); | |
} else { | |
$rows = array(); | |
while ($row = $result->fetch_array($resulttype)) { | |
$rows[] = $row; | |
} | |
} | |
if ($resulttype !== MYSQLI_NUM) { | |
$names = array(); | |
foreach ($fields as $i => $field) | |
$names[] = $field->name; | |
$fields = array_combine($names, $fields); | |
} | |
if ($rows) { | |
foreach ($rows as &$row) { | |
foreach ($fields as $i => $field) { | |
switch ($field->type) { | |
case MYSQLI_TYPE_DECIMAL: | |
case MYSQLI_TYPE_DOUBLE: | |
case MYSQLI_TYPE_LONGLONG: | |
case MYSQLI_TYPE_FLOAT: | |
$row[$i] = (double) $row[$i]; | |
break; | |
case MYSQLI_TYPE_BIT: | |
case MYSQLI_TYPE_TINY: | |
case MYSQLI_TYPE_SHORT: | |
case MYSQLI_TYPE_LONG: | |
case MYSQLI_TYPE_INT24: | |
case MYSQLI_TYPE_YEAR: | |
$row[$i] = (int) $row[$i]; | |
break; | |
default: | |
break; | |
} | |
} | |
} | |
unset($row); | |
} | |
return $rows; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment