php while循环仅显示数据库中的最后一行

时间:2018-10-09 02:13:38

标签: php pdo

我正在尝试以JSON格式列出数据库中的所有行(当前为2),但我得到的唯一输出是最后一行。

输出:

[{"id":"2","Name":"Googleplex","Address":"1600 Amphitheatre Pkwy, Mountain View, CA","Latitude":"37.421999","Longitude":"-122.083954"}]

代码:

if($status == "connected") {
      $locations = $db->prepare('SELECT * FROM Locations');
      $locations->execute();
      $result = $locations->fetch(PDO::FETCH_ASSOC);

  if(!empty($result)) {
    // If so, then create a results array and a temporary one
    // to hold the data
    $resultArray = array();
    $tempArray = array();

    // Loop through each row in the result set
    while($row = $locations->fetch(PDO::FETCH_ASSOC))
    {
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    // Finally, encode the array to JSON and output the results
    echo json_encode($resultArray);
  }
}

1 个答案:

答案 0 :(得分:1)

问题是您要丢弃在这一行中读取的第一个结果:

 $result = $locations->fetch(PDO::FETCH_ASSOC);

您可以将代码简化为

if ($status == "connected") {
    $locations = $db->prepare('SELECT * FROM Locations');
    $locations->execute() or die("Unable to execute query");
    $resultArray = array();
    while ($row = $locations->fetch(PDO::FETCH_ASSOC)) {
        $resultArray[] = $row;
    }
    echo json_encode($resultArray);
}