PHP文件只返回一个(最新的)JSON对象


PHP file only returns one (latest) JSON object

在对服务器执行GET请求时,我设置的.PHP文件只返回最新的JSON对象,而不是整个数组。我认为它会被数组覆盖,而不是添加到数组中,但我对PHP不太熟悉,可能会指向正确的方向。

感谢您提前提供任何帮助,代码如下。

<?php
$result = mysql_query("SELECT * FROM books WHERE uni_year = '$uni_year' AND uni_course = '$uni_course'") or die(mysql_error());
if(!empty($result)) {
    if (mysql_num_rows($result) > 0) {
        $result = mysql_fetch_array($result);
       // $result = mysql_fetch_array($result);
       // while($row = mysql_fetch_array($result)){
        // temp array
        $books = array();
        $books["list_id"] = $result["list_id"];
        $books["book_title"] = $result["book_title"];
        $books["uni_course"] = $result["uni_course"];
        $books["uni_year"] = $result["uni_year"];
        $books["book_author"] = $result["book_author"];
        $books["book_price"] = $result["book_price"];
        $books["book_year"] = $result["book_year"];
        $books["isbn"] = $result["isbn"];
    //}
        // success
        $response["success"] = 1;
        // user node
        $response["books"] = array();
        array_push($response["books"], $books);
    } else {
        $response["success"] = 0;
        $response["message"] = "num of rows bigger than zero";
    }
} else {
        $response["success"] = 0;
        $response["message"] = "No product found";
        echo json_encode($response);
}

    echo json_encode($response);
} else {
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
    echo json_encode($response);
}
?>

您只从结果($result = mysql_fetch_array($result);)中获取第一条记录。

你需要在一个循环中获取它们:

<?php
$result = mysql_query("SELECT * FROM books WHERE uni_year = '$uni_year' AND uni_course = '$uni_course'") or die(mysql_error());
if(!empty($result)) {
    if (mysql_num_rows($result) > 0) {
        $books = array();
        while($row = mysql_fetch_array($result)){
            $book = array();
            $book["list_id"] = $row["list_id"];
            $book["book_title"] = $row["book_title"];
            $book["uni_course"] = $row["uni_course"];
            $book["uni_year"] = $row["uni_year"];
            $book["book_author"] = $row["book_author"];
            $book["book_price"] = $row["book_price"];
            $book["book_year"] = $row["book_year"];
            $book["isbn"] = $row["isbn"];
            $books[] = $book;
        }
        // success
        $response["success"] = 1;
        // user node
        $response["books"] = $books;
    } else {
        $response["success"] = 0;
        $response["message"] = "num of rows bigger than zero";
    }
} else {
    $response["success"] = 0;
    $response["message"] = "No product found";
}

echo json_encode($response);