Skip to content

Instantly share code, notes, and snippets.

@oscar-broman
Created January 16, 2013 09:13
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 oscar-broman/4545758 to your computer and use it in GitHub Desktop.
Save oscar-broman/4545758 to your computer and use it in GitHub Desktop.
Fetch MySQLi results properly typed.
<?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