JSON编码缺少MySQL的第一行

时间:2015-02-21 10:51:46

标签: php mysql json fetch

我正在尝试将表中的所有行编码为JSON,但似乎错过了第一行。

$sql = "SELECT * FROM NewsStream";
$result = $conn->query($sql);

if ($result->num_rows > 0) {

    while($row = $result->fetch_assoc()) {
        echo "echo: " . $row["id"]. "  " . $row["title"]. " " . $row["content"]. "<br />";
        echo "JSON: " . json_encode($row). "<br />";
    }
}

结果是:

echo: 0 title content
JSON: 
echo: 1 abc efg
JSON: {"id":"1","title":"abc","content":"efg","type":"11","author":"12","preview":"13","src":"14","date":"2015-02-20"}
echo: 2 4563 456465
JSON: {"id":"2","title":"4563","content":"456465","type":"54","author":"5463","preview":"6454","src":"456","date":"2015-02-12"}

为什么第一个“JSON:”缺失而回显结果是对的?

2 个答案:

答案 0 :(得分:0)

试试这个

$return_arr = array();

$fetch = mysql_query("SELECT * FROM NewsStream");

while ($row = mysql_fetch_assoc($fetch)) {
$data=array();  
 foreach ($row as $key => $value) {
    $data[$key]=$value;
 }
 $return_arr[] = $data;
}
echo json_encode($return_arr);

答案 1 :(得分:0)

试试这个:

$sql = "SELECT * FROM NewsStream";
$rows = array();
while($r = mysqli_fetch_assoc($sql)) {
    $rows[] = $r;
}
print json_encode($rows)
相关问题