Development

How to return integers and floats from MySQL with PHP PDO

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.

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago