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

Leave Comment