【发布时间】:2015-11-18 17:37:15
【问题描述】:
在对我的服务器执行 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);需要一个while循环......就像你的代码中注释掉的那个......除了循环必须一直到array_push($response["books"], $books);跨度> -
而且您不需要将所有这些单独的列分配给 $books.... 从数据库中只选择您需要的列,并作为关联数组获取,然后推送 $result (行)到 $response['books']
-
然后进入21世纪,用准备好的语句和绑定变量切换到MySQLi或PDO
标签: php arrays json object response