php脚本使用json编码只加载第一条记录

时间:2018-01-29 19:07:19

标签: php mysql json encode selectall

<?php
require_once 'connect.php' ;

$sql = "SELECT Title,Date,Time,Location,image_url FROM events ";

$result = $conn->query($sql);

if ($result->num_rows > 0) {


    $data = array();
    while($row = $result->fetch_assoc()) {
       $data['events'] = $row ;

    }

} 


echo json_encode($data); 
header('Content-Type: application/json');

?> 

1 个答案:

答案 0 :(得分:5)

在列表中插入条目,只有一些小建议

require_once 'connect.php' ;

$sql = "SELECT Title,Date,Time,Location,image_url FROM events ";

$result = $conn->query($sql);

// Move $data declaration up for zero result.
$data = array('events' => []);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
       // Insert $rows in events array
       $data['events'][] = $row ;

    }
} 

// Send headers first before sending any data
header('Content-Type: application/json');
echo json_encode($data);