Monday, January 25, 2010

json_encode pg_fetch_array

For some reason you need to run the result of pg_fetch_array through a loop and store in another array to be able to encode as JSON ... here's an example:

// Connecting, selecting database
$dbconn = pg_connect("host=HOSTNAME dbname=DBNAME user=DBUSER password=PASSWORD")
or die('Could not connect: ' . pg_last_error());

// Performing SQL query
$query = "SELECT * FROM mytable";
$result = pg_query($query) or die('Query failed: ' . pg_last_error());

$resultArray = array();
while ($row = pg_fetch_array($result, null, PGSQL_ASSOC)) {
$resultArray[] = $row;
}

echo json_encode($resultArray);

// Free resultset
pg_free_result($result);

// Closing connection
pg_close($dbconn);

3 comments:

Mick said...

This works for me!!

$arr = pg_fetch_all($result1);
echo json_encode($arr);

KE5DEV said...

Excellent. Simple and elegant. Thanks for the snippet!

Papa Neto said...

mano, tu é foda pra caralho! valeu ai, TE AMO SZ