Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve SQL data type when using mysqli non-prepared statements

Tags:

mysql

I would like to use non-prepared statements using mysqli in PHP and preserve the SQL data type.

The comparison table on this page on php.net it suggests that it is possible to do this:

Result set values SQL data types

Prepared Statement: Preserved when fetching

Non-prepared statement: Converted to string or preserved when fetching

What is meant by fetching?

At present, in code like the following column values are all string. Is there a way to preserve data type without using prepared statements?

$conn = new mysqli('db_host', 'db_username', 'db_password', 'db_name');
$conn->set_charset('db_charset');
$result = $conn->query($sql, MYSQLI_USE_RESULT);
$row = $result->fetch_assoc();

NB. unbuffered query

like image 227
johna Avatar asked Mar 07 '18 04:03

johna


1 Answers

I have since found the option mysqli MYSQLI_OPT_INT_AND_FLOAT_NATIVE that converts numeric columns to int or float (boolean columns become int).

I'm not sure if this is what was referred to in the php.net documentation or if there is another method.

Example:

$conn->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
like image 57
johna Avatar answered Sep 17 '22 23:09

johna