I like mastermind's technique, but the coding can be simpler:
function cast_query_results($result): array
{
if ($result === false)
return null;
$data = array();
$fields = $result->fetch_fields();
while ($row = $result->fetch_assoc()) {
foreach ($fields as $field) {
$fieldName = $field->name;
$fieldValue = $row[$fieldName];
if (!is_null($fieldValue))
switch ($field->type) {
case 3:
$row[$fieldName] = (int)$fieldValue;
break;
case 4:
$row[$fieldName] = (float)$fieldValue;
break;
// Add other type conversions as desired.
// Strings are already strings, so don't need to be touched.
}
}
array_push($data, $row);
}
return $data;
}
I also added checking for query returning false rather than a result-set.
And checking for a row with a field that has a null value.
And if the desired type is a string, I don't waste any time on it - its already a string.
I don't bother using this in most php code; I just rely on php's automatic type conversion. But if querying a lot of data, to then perform arithmetic computations, it is sensible to cast to the optimal types up front.
$conn->query("your query")
i got the integer fields as string but when i used$conn->prepare("your query")
i got the parameters as they were in the database – Landahl