Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDOStatement to JSON [closed]

Tags:

json

php

pdo

How would I convert a PDOStatement to JSON?

I need to jsonify a PDO::FETCH_OBJ.

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

like image 467
manumoomoo Avatar asked May 05 '10 02:05

manumoomoo


2 Answers

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

To encode 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); 
like image 116
Rwky Avatar answered Sep 29 '22 19:09

Rwky


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)); 
like image 27
Amber Avatar answered Sep 29 '22 19:09

Amber