Цикл php while показывает только последнюю строку в базе данных - PullRequest
0 голосов
/ 09 октября 2018

Я пытаюсь перечислить все строки в базе данных (в настоящее время 2) в формате JSON, но единственный вывод, который я получаю, - это последняя строка.

Выход:

[{"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 голосов
/ 09 октября 2018

Проблема в том, что вы отбрасываете первый результат, который вы прочитали в этой строке:

 $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);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...