AJAX响应和PHP循环

I am using PHP to retrieve some records from a MySQL database, I would like to send these to my AJAX and loop through them, in order to prepend rows to an existing table.

However I can only see the last (most recent) record returned from my query. Could someone please point out where I am going wrong?

AJAX:

$.ajax({
    type: "POST",
    url: 'feed.php',
    data: {lastSerial: true},
    dataType: 'json',
    success: function(data){
        console.log(data); // logs `{Direction: "O", CardNo: "02730984", SerialNo: 20559303}`
        $.each(data, function(key, value) {
            // here I want to loop through the returned results - for example
            $("#transactionTable").prepend('<tr><td>'+ SerialNo +'</td><td>'+ CardNo +'</td><td>'+ Direction +'</td></tr>');
        });
       }
   });

feed.php

if(isset($_POST['lastSerial']) && $_POST['lastSerial'] == true) {
  $query = "SELECT TimeStamp, Direction, CardNo, SerialNo FROM Transactions";
  // this query returns approx. 20 results
  $stmt = $conn->prepare($query);
  $stmt->execute();
  $result = $stmt->get_result();
  while($row = $result->fetch_assoc()) {
        $data["Direction"] = $row['Direction'];
        $data["CardNo"] =   $row['CardNo'];
        $data["SerialNo"] = $row['SerialNo'];
  }
  echo json_encode($data);
}

Also in my PHP, should I be using a while or if statement?

You're using a single $data object and resetting its contents each time. You want to build an array of objects:

$data = array();

while($row = $result->fetch_assoc()) {
  $data[] = array( 
    "Direction" => $row['Direction'],
    "CardNo"    => $row['CardNo'],
    "SerialNo"  => $row['SerialNo']
  );
}

echo json_encode($data);

Followed by:

success: function(data) {
    $.each(data, function(key, value) {
        $("#transactionTable").prepend(
          '<tr><td>' + value.SerialNo + '</td>' +
          '<td>' + value.CardNo + '</td>' +
          '<td>'+ value.Direction +'</td></tr>');
    });
}

In your feed.php you loop through the results, but on each loop you overwrite the data. Thus, you are only returning the last result from the database to the AJAX request.

Many solutions exist, but you have to do something like

$data["Direction"][] = $row['Direction'];
$data["CardNo"][] =   $row['CardNo'];
$data["SerialNo"][] = $row['SerialNo'];

or better:
$data[] = $row;

Since you dont change the key, you can use the last option. With jQuery you can loop over it, and access the data with value.Direction, value.CardNo, value.SerialNo

note: not tested