Categories: 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…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago