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.

PHP PDO MySQL int float bool types json

The following example SELECT code:

header('Content-Type: application/json');

$db = new PDO('mysql:host=;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.