在php中以json格式更改从服务器获取的数据
问题描述:
ive got a script in php which fetched data from server, but i want to encode it in json format.
<?php
// attempt a connection
$dbh = pg_connect("host=10.22.35.11 dbname=iwmp_dev2 user=postgres ");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// execute query
//$sql = $_POST['pLat'];
$sql = "SELECT officer_name FROM iwmp_officer";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
$array = array();
while ($row = pg_fetch_assoc($result)) {
$i++;
$comm = implode(",",$row);
echo json_encode($comm);
}
// free memory
pg_free_result($result);
// close connection
pg_close($dbh);
?>
but my ouptput is coming in format
"V. M. ARORA""Dr. C. P. REDDY""ARTI CHOWDHARY""JAGDISH SINGH" also when using implode func on *pgsql_fetch_assoc*, no ","(coma's) are coming.
please help
答
Try this;
while ($row = pg_fetch_assoc($result)) {
echo json_encode($row);
}
答
You don't need to implode the $row
. Try replacing your while loop with below code
while ($row = pg_fetch_assoc($result)) {
echo json_encode($row);
}
答
I think you're doing it in wrong way. Try to do like below.
while ($row = pg_fetch_assoc($result)) {
$rows[] = $row;
}
echo json_encode($rows);