neiza neiza - 5 months ago 20
PHP Question

encode php recordset in custom format

I'm currently have a recordset created with dreamweaver and have encode the results in json format which work fine.

Recordset

$maxRows_rs_feeds = 3;
$pageNum_rs_feeds = 0;
if (isset($_GET['pageNum_rs_feeds'])) {
$pageNum_rs_feeds = $_GET['pageNum_rs_feeds'];
}
$startRow_rs_feeds = $pageNum_rs_feeds * $maxRows_rs_feeds;

mysql_select_db($database_vivalooks, $vivalooks);
$query_rs_feeds = "SELECT fname,lname FROM profile";
$query_limit_rs_feeds = sprintf("%s LIMIT %d, %d", $query_rs_feeds, $startRow_rs_feeds, $maxRows_rs_feeds);
$rs_feeds = mysql_query($query_limit_rs_feeds, $vivalooks) or die(mysql_error());
$row_rs_feeds= mysql_fetch_assoc($rs_feeds);

if (isset($_GET['totalRows_rs_feeds'])) {
$totalRows_rs_feeds = $_GET['totalRows_rs_feeds'];
} else {
$all_rs_feeds = mysql_query($query_rs_feeds);
$totalRows_rs_feeds = mysql_num_rows($all_rs_feeds);

}
$totalPages_rs_feeds = ceil($totalRows_rs_feeds/$maxRows_rs_feeds)-1;

do {

echo json_encode($row_rs_feeds);
} while ($row_rs_feeds = mysql_fetch_assoc($rs_feeds));

mysql_free_result($rs_feeds);


Recordset Results

{"fname":"Benjamin","lname":"Blay"}{"fname":"Alfread","lname":"Mark"}{"fname":"yaa","lname":"tiwaa"}


But i want the results to be encode like this rather

[{"fname":"Benjamin","lname":"Blay"},{"fname":"Alfred","lname":"Mark"},{"fname":"yaa","lname":"tiwaa"}]

Answer

Try

do { 
    $json[]=json_encode($row_rs_feeds);
} while ($row_rs_feeds = mysql_fetch_assoc($rs_feeds));
echo "[".implode(", ", $json)."]";

OR

do { 
     $rows[] = $row_rs_feeds;
} while ($row_rs_feeds = mysql_fetch_assoc($rs_feeds));

echo json_encode($rows);
Comments