开发者

php json_encode misses first record

i am retriving a .php file which json_encodes the results from a record开发者_运维技巧set.

it produces the json fine but it misses the first record in the recordset,

so if i have 21 rows it only creates a json object with 20 records, with the first one missing.

function recordSetToJson($mysql_result) {
 $rs = array();
 while($rs[] = mysql_fetch_assoc($mysql_result)) {
    // you don´t really need to do anything here.
  }
 return json_encode($rs);
}
echo '{"myFiles":'.recordSetToJson($UserFiles).'}';

i tried:

function recordSetToJson($mysql_result) {
 $rs = array();
 do{
    // you don´t really need to do anything here.
  }
 return json_encode($rs);
}while($rs[] = mysql_fetch_assoc($mysql_result)) 
echo '{"myFiles":'.recordSetToJson($UserFiles).'}';

but this just produces a blank page.


I suggest building an Array that holds all data and then encode it using json_encode, it is much simpler and easy to maintain.

function recordSetToJson($mysql_result) {
 $rs = array();
 while($row = mysql_fetch_assoc($mysql_result)) {
    array_push($rs,$row);
  }
 return json_encode($rs);
}
echo '{"myFiles":'.recordSetToJson($UserFiles).'}';


simple solution!!!

i added mysql_data_seek($mysql_result, 0); to the function to reset the recordset back to the first row, don't know why it was forwared by 1 record in the firstplace but, it works now.

the full function:

<?php 
    function recordSetToJson($mysql_result) {
        $rs = array();
        mysql_data_seek($mysql_result, 0);
        while($rs[] = mysql_fetch_assoc($mysql_result)) {
            // dont need anything here!!
        }
        return json_encode($rs);
    };
echo '{"myFiles":'.recordSetToJson($UserFiles).'}';
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜