Как получить все категории продуктов из mysql db через php и вернуть json array

У меня есть приложение для Android. Я хочу отправить запрос на получение в файл get_categories.php. В файле get_categories.php я хочу

$query_categories = "SELECT category_name FROM categories"; 

и вернуть все категории, найденные в этой таблице, в массив json.

Как я могу это сделать?

Это мой неполный код:

 if (!empty($_GET)) { $query_categories = "SELECT category_name FROM categories"; $success = false; try{ $sth = $connection->prepare($query_categories); //$sth->execute(array(':user_id' => $user_id)); //$user_items_count = $sth->rowCount(); - these are lines from other php file I've used foreach($)//?? $success = true; } catch (PDOException $ex) { $response["success"] = 0; $response["message"] = $ex; die(json_encode($response)); $connection = null; } if($success) { $response["success"] = 1; $response["message"] = "Kylie"; die(json_encode($response)); $connection = null; } else { $response["success"] = 2; $response["message"] = "something went wrong"; die(json_encode($response)); $connection = null; } } else { $response["success"] = 3; $response["message"] = "Another brick in the wall"; echo json_encode($response); $connection = null; } 

Позже, в моем Java-коде, как мне его декодировать? Обычно до этого момента, в других моих передачах JSON, я получил нормальный объект Json без массивов и читал их следующим образом:

 setUserLastSeen(json.getString(TAG_USER_LAST_SEEN)); //for example. 

Но как мне декодировать массив?

Для php стороны это, как вы можете получить массив категорий и сделать json, для подготовленных операторов это то, как вы можете выполнить

 $success = false; try { $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); $success = true; } catch(PDOException $e) { $response["success"] = 0; $response["message"] = 'Connection failed: ' . $e->getMessage(); $response["data"]=null; die(json_encode($response)); } $query_categories = "SELECT category_name FROM categories"; try{ $sth = $sth->prepare($query_categories ); $success = true; } catch(PDOException $e) { $response["success"] = 0; $response["message"] = 'Prepare failed: ' . $e->getMessage(); $response["data"]=null; die(json_encode($response)); } try{ $sth->execute(); $success = true; } catch(PDOException $e) { $response["success"] = 0; $response["message"] = 'Execute failed: ' . $e->getMessage(); $response["data"]=null; die(json_encode($response)); } $categories = $sth->fetchAll(PDO::FETCH_COLUMN, 0);/* fetches all categories from db */ /* Output of $query_categories Array ( [0] => cat1 [1] => cat2 [2] => cat3 [3] => cat4 ) */ /* json encode $query_categories ["cat1","cat2","cat3","cat4"] */ /* check if categories exist or not*/ if(empty($categories)){ $response["success"] = 0; $response["message"] = "No categories found"; $response["data"]=null; die(json_encode($response)); $connection = null; } if($success) { $response["success"] = 1; $response["message"] = "Kylie"; $response["data"]=$categories; die(json_encode($response)); $connection = null; /* output {"success":0,"message":"Kylie","data":["cat1","cat2","cat3","cat4"]} */ } else { $response["success"] = 2;/* don't where you are setting success to 2*/ $response["message"] = "something went wrong"; $response["data"]=null; die(json_encode($response)); $connection = null; } } else { $response["success"] = 3;/* don't where you are setting success to 3*/ $response["message"] = "Another brick in the wall"; $response["data"]=null; die(json_encode($response)); $connection = null; } 

Я плохо разбираюсь в java, но вот ссылка. Как разобрать JSON и превратить его значения в массив?

 /* store json string in the_json */ JSONObject myjson = new JSONObject(the_json); JSONArray the_json_array = myjson.getJSONArray("data"); 

Примечание: убедитесь, что на стороне Java вы должны проверить успех от json, который должен быть == 1, а the_json_array не равен нулю

Объекты данных PHP

вы можете использовать приведенный ниже код для обработки данных с помощью json, а затем декодировать этот массив json:

================================================== ============================================ {

  HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("your webservice"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse res = httpclient.execute(httppost); HttpEntity entity = res.getEntity(); is = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); sb.append(reader.readLine() + "\n"); String line="0"; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result=sb.toString(); Log.d("Data",""+ result); } catch(Exception e) { Log.e("log_tag", "Error converting result "+e.toString()); } String fd_ono=null; try { JSONArray jArray = new JSONArray(result); JSONObject json_data=null; for(int i=0;i<jArray.length();i++) { json_data = jArray.getJSONObject(i); fd_ono=json_data.getString("your column name"); textView.settext(fd_ono.toString()); } } catch(JSONException e1) { Toast.makeText(getBaseContext(), "Record not found", Toast.LENGTH_LONG).show(); }