Home > Mobile >  How to force mysqli results to strings to support legacy code
How to force mysqli results to strings to support legacy code

Time:10-23

Prepared queries in mysqli return numeric database columns as PHP numbers, as does the mysqlnd driver using the MYSQLI_OPT_INT_AND_FLOAT_NATIVE option.

I am modernizing a legacy codebase to use parameterized queries. Other areas of the code rely on the query results having string data types, e.g.:

if ($object->isTrue() === '1') { }

The best solution I've come up to make the output match the expectations of the existing code is to manually cast each result back to strings:

$data = [];
while ($row = $result->fetch_assoc()) {
  array_walk($row, function(&$field) { $field = (string) $field; });
  $data[] = $row;
}

Is there a more efficient/effective way to do this?

CodePudding user response:

There is no way to force mysqli prepared statements to cast all values to a string. Binary protocol transfers the data using native types and there is no option in mysqli to cast the values to string.

If you have such a requirement as part of a legacy project, you can cast it yourself by mapping each value in every row as a string.

$arr = [];
foreach ($stmt->get_result() as $row) {
    $arr[] = array_map(strval::class, $row);
    // or if you support only PHP 8.1
    // $arr[] = array_map(strval(...), $row);
}
  • Related