manumoomoo manumoomoo - 4 months ago 18
JSON Question

PDOStatement to json

How would I convert a

PDOStatement
to json? Is there library out there to do this?

EDIT: I need to jsonify a
PDO::FETCH_OBJ
. Sorry, thanks for all of the responses.

json_encode
does not have the ability to jsonify a
PDO::FETCH_OBJ
.

Thanks.

Answer

You can use the inbuilt php function json_encode() http://php.net/manual/en/function.json-encode.php

To encode the statement use something like this:

<?php
$pdo=new PDO("mysql:dbname=database;host=127.0.0.1","user","password");
$statement=$pdo->prepare("SELECT * FROM table");
$json=json_encode($statement);
?>

To encode just the results use something like

<?php
$pdo=new PDO("mysql:dbname=database;host=127.0.0.1","user","password");
$statement=$pdo->prepare("SELECT * FROM table");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
?>