How to return numerics in JSON data from a PHP PDO MySQL query. Usually and as default all of the data is returned as strings.
The following example SELECT code:
<?php
header('Content-Type: application/json');
$db = new PDO('mysql:host=127.0.0.1;dbname=test;charset=utf8mb4', 'root', '');
$select = $db->query("SELECT * FROM `example1`;");
echo json_encode($select->fetch(PDO::FETCH_ASSOC)); Will return
{
"id": "5286",
"classname": "GoldApple",
"price": "2.2",
"quantity": "80",
"instock": "1",
"brand": "Green Orchards",
"updated": "2021-06-09 12:42:38"
} To not show numbers as strings the following PDO attributes need to be set after the connection is made:
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $db->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);
To disable emulation on prepared statements and also convert numeric values to string disabled.
The returned data will now look like this:
{
"id": 5286,
"classname": "GoldApple",
"price": 2.2,
"quantity": 80,
"instock": 1,
"brand": "Green Orchards",
"updated": "2021-06-09 12:42:38"
} Whereby the values have correct data formatting with numerics and strings.
Â
A drained and empty Kennington reservoir images from a drone in early July 2024. The…
Merrimu Reservoir from drone. Click images to view larger.
Some early September spring shots from a bushwalk, It is still too early for wildflowers.
I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…
If you ever needed a simple solution in Laravel to delete an entire directory and…
How to enforce only one user to register or be registered in a Laravel web…