Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP PDO - Why is my fetchAll() converting all values to a string when using json_encode?

Tags:

php

I'm doing a select all SQL query on a table and running it in a prepared query in PHP. I'm then echoing the result inside a json_encode. The result is putting every value as a string, even the row ID which is an INT. How do you keep the original value types ?

    $sql = "SELECT * FROM `Type`";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($result);

The output is as follows:

[{"ID":"1","Type":"Classic Starters","Description":""},{"ID":"2","Type":"Special Starters","Description":""}]

The desired output is as follows:

[{"ID":1,"Type":"Classic Starters","Description":""},{"ID":2,"Type":"Special Starters","Description":""}]

Thanks in advance <3

like image 958
JamMan9 Avatar asked Oct 17 '25 07:10

JamMan9


1 Answers

$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

this resolve my problem

like image 61
LitileXueZha Avatar answered Oct 19 '25 23:10

LitileXueZha