2

If I make a simple query using PDO like this:

$dbh = new PDO("mysql:host=localhost;dbname=nameofDb", "root", ""); 

$sql = "select
        w.id,
        w.col,
        w.name,
        w.row,
        w.sizeX,
        w.sizeY,
    from
        widget as w         
    where
        w.dashboard_id= ? ";


$stmt = $dbh->prepare($sql);
$stmt->execute(array($id));
$widgets = $stmt->fetchAll(PDO::FETCH_ASSOC);
$db = null;

var_dump($widgets);

And try to dump I get this:

object(stdClass)[3]
  public 'dashboard_id' => string '1' (length=1)
  public 'id' => string '10' (length=2)
  public 'col' => string '3' (length=1)
  public 'name' => string 'ggg' (length=3)
  public 'row' => string '1' (length=1)
  public 'sizeX' => string '1' (length=1)
  public 'sizeY' => string '1' (length=1)

All values are returned as string, but col,row, sizeX,sizeY are all numbers. The problem here is that if I try to output this object as json I will get

{"dashboard_id":"1","id":"10","col":"3","name":"myName",
    "row":"1","sizeX":"1","sizeY":"1"}

with all numbers in double quotes, instead I would like to have numer without quotes.

So, there is no native way for php to json encode a query and mantain the correct format?

Tropicalista
  • 3,097
  • 12
  • 44
  • 72
  • Convert them manually to integers. PHP can't do this conversion for you since it doesn't know that MySQL stores something as integer or whatever else. – N.B. Aug 28 '14 at 10:05
  • 1
    Not sure if this would work for you, but you could try binding your result before fetching. like: `$stmt->bind_result($widgets);$stmt->fetchAll(PDO::FETCH_ASSOC);` – CrazySabbath Aug 28 '14 at 10:15
  • @CrazySabbath - isn't that `bind_result` mysqli only? – N.B. Aug 28 '14 at 10:20
  • My mistake, you're right, it's mysqli function. – CrazySabbath Aug 28 '14 at 10:26

0 Answers0