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.
Using FTP and PHP to get an array of file details such as size and…
Creating and using Laravel form requests to create cleaner code, separation and reusability for your…
Improving the default Laravel login and register views in such a simple manner but making…
Laravel validation for checking if a field value exists in the database. The validation rule…