tags:

views:

34

answers:

3

How would I convert a PDOStatement to json?

Is there lib 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.

A: 

Use the fetchAll() method of the PDOStatement to retrieve an array of the values, and then pass that to json_encode().

$resultJSON = json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
Amber
A: 
$array = $statement->fetchAll( PDO::FETCH_ASSOC );
$json = json_encode( $array );
Galen
A: 

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");
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
?>
Obsidian
did you just json_encode a PDOStatement object?
Galen
Yes I did which sort of works, when decoding it returns a stdClass object.@mediaslave you can use json_encode on PDO::FETCH_OBJ, when you run PDO::FETCH_OBJ it creates objects of the stdClass, these can then be encoded into json objects which then decode back into stdClass objects. Do some var_dumps on your results and see :)
Obsidian