PHP: can't encode json with multiple rows

前端 未结 5 799
旧时难觅i
旧时难觅i 2020-12-10 17:49

I\'ve spent a couple of hours looking through several the similar answers before posting my problem.

I\'m retrieving data from a table in my database, and I want to

5条回答
  •  庸人自扰
    2020-12-10 18:01

    The problem is you're spitting out separate JSON for each row, as opposed to doing it all at once.

    $result = mysql_query($query);
    
    $rows = array();
    
    //retrieve and print every record
    while($r = mysql_fetch_assoc($result)){
        // $rows[] = $r; has the same effect, without the superfluous data attribute
        $rows[] = array('data' => $r);
    }
    
    // now all the rows have been fetched, it can be encoded
    echo json_encode($rows);
    

    The minor change I've made is to store each row of the database as a new value in the $rows array. This means that when it's done, your $rows array contains all of the rows from your query, and thus you can get the correct result once it's finished.

    The problem with your solution is that you're echoing valid JSON for one row of the database, but json_encode() doesn't know about all the other rows, so you're getting a succession of individual JSON objects, as opposed to a single one containing an array.

提交回复
热议问题