首页 > 解决方案 > php while循环只显示数据库中的最后一行

问题描述

我正在尝试以 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);
  }
}

标签: phppdo

解决方案


问题是你丢弃了你在这一行中读到的第一个结果:

 $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);
}

推荐阅读