Iam using PHP (5.6.8) to act as the middle tier between a MySQL database and returning the results in JSON format.
We are using the PHP extension (PDO) to do the database interaction, but have noticed that all numeric values get returned as a string. The database itself is running on a Linux installation, but during development, both the client and middle tier are running on Windows.
I set the connection parameter "ATTR_STRINGIFY_FETCHES" to false but that made no difference. e.g. $dbConnection->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);
This is the PHP function that I am using to retrieve data and it is tied to the RESTful interface.
function getAllObjects()
{
$sql = "SELECT * FROM Tbl_Objects ORDER BY 1";
try {
$db = getDB();
$stmt = $db->query($sql);
$objects = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($objects);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
I also tried "mysqli" but I get the same results in that the numeric values are all converted to Strings. If I use the "cast_query_results($rs)" function on the net, I do get numeric converted correctly, but it seems to me that this is rather a fudge, rather than a solution.
Any ideas on how to get this to work natively please?
Alternatively you can force json_encode()
to convert string numbers to integers with:
json_encode($objects, JSON_NUMERIC_CHECK);
So you have to make sure that mysqlnd is shown under PDO section in phpinfo()
and PDO::ATTR_EMULATE_PREPARES
setting is set to FALSE
.
Note that decimal
values will be always returned as strings, as they always should be.
Excellent. I am still a bit of a newbie to PHP, so the json_encode option works best for me.