我试图检索多行JSON数据并显示它但我无法检索所有行,我只得到数据库表的顶部(第一行)。我很困惑我怎么能把检索到的JSON将数据转换成某种数组并访问各行?
我提供了与问题相关的代码。 是的,我在发布这个问题之前做了足够的研究。我实际上发现了一个问题,这个问题与我的相似,但是没有人回答,所以我正在撰写这篇文章。
谢谢
下面是我的Freebies.java类中的代码,我试图通过从UserFunctions.java类调用getAllFreebies函数来检索JSONdata
UserFunctions uf = new UserFunctions();
JSONObject json = uf.getAllFreebies();
System.out.println(json);
以下是UserFunctions.java类中函数getAllFreebies()的代码
public JSONObject getAllFreebies(){
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", getAllFreebies_tag));
JSONObject json = jsonParser.getJSONFromUrl(getAllFreebiesURL,params);
return json;
}
以下是index.php中的代码,其中我从DB_Function.php文件调用getFreebies()函数
else if($tag = 'getAllFreebies'){
$getAllFreebies = $db->getFreebies($username,$catagory,$subcatagory,$title,$condition,$description,$address,$city,$state,$country,$zipcode,$posted_on);
if($getAllFreebies)
{
$response["success"] = 1;
$response["getAllFreebies"]["username"] = $getAllFreebies["username"];
$response["getAllFreebies"]["catagory"] = $getAllFreebies["catagory"];
$response["getAllFreebies"]["subcatagory"] = $getAllFreebies["subcatagory"];
$response["getAllFreebies"]["title"] = $getAllFreebies["title"];
$response["getAllFreebies"]["item_condition"] = $getAllFreebies["item_condition"];
$response["getAllFreebies"]["description"] = $getAllFreebies["description"];
$response["getAllFreebies"]["address"] = $getAllFreebies["address"];
$response["getAllFreebies"]["city"] = $getAllFreebies["city"];
$response["getAllFreebies"]["state"] = $getAllFreebies["state"];
$response["getAllFreebies"]["country"] = $getAllFreebies["country"];
$response["getAllFreebies"]["zipcode"] = $getAllFreebies["zipcode"];
$response["getAllFreebies"]["posted_on"] = $getAllFreebies["posted_on"];
echo json_encode($response);
}else {
$response["error"] =1;
$response["error_msg"] = "Error in getAllFreebies";
echo json_encode($response);
}
}// end of getAllFreebies tag
下面是DB_function.php的getFreebies()函数的代码,它负责在MySQL数据库上执行查询。
public function getFreebies(){
$result = mysql_query("SELECT * FROM freebie") or die(mysql_error());
return mysql_fetch_array($result);
}
下面是logcat:
05-30 00:13:23.960: E/JSON(318): {"tag":"getAllFreebies","success":1,"error":0,"getAllFreebies":{"username":"viking","catagory":"Art","subcatagory":"Potrait","title":"Potrait","item_condition":"Good","description":"potarit","address":"Blah St","city":"lalaland","state":"NA","country":"NA","zipcode":"blah","posted_on":"2012-05-27"}}
答案 0 :(得分:3)
mysql_fetch_array()仅将查询结果集的单行作为数组返回。它不会获取所有行。由于您从getFreebies方法返回了fetch的结果,而不是结果句柄本身,因此调用代码不可能从查询中获得任何其他结果,除了您输入的那一行之外取出。
因此,您应该:
public function getFreebies() {
$result = ...
return($result);
}
和
$getAllFreebies = $db->getFreebies(...);
$data = array();
while($row = mysql_fetch_assoc($getAllFreebies)) {
$data[] = array(
.... your variable assignments here ...
);
}
echo json_encod($data);