私はJava/AndroidアプリにMySQLデータベースとPHPを使用しています。私はphpの経験がありません。
これは私のphpファイル(getAllDataFromSomeTable.php)です
<?php
mysql_connect("someHosturl","someUsername","somePassword");
mysql_select_db("databasename");
$q=mysql_query("SELECT * FROM sometable");
while($e=mysql_fetch_assoc($q))
$output[]= $e;
print(json_encode($output));
mysql_close();
?>
そして私はJavaでHttpPostsやそのようなものを使っています。このようにして、「sometable」からすべてのデータを取得できます
しかし、たとえば「username='thisuser'であるテーブルからトップ1を選択する」のような別のクエリを使用したい場合。Javaで動的に変更するにはどうすればよいですか?私のphpファイルはどのように見えるべきですか?Javaのコードはどのように見えるべきですか?これは私が今持っているコードです:
String result = "";
List<? extends NameValuePair> licenses = (List<? extends NameValuePair>) new ArrayList<DriversLicense>();
InputStream is = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://some-url.com/getAllDataFromSomeTable.php");
httpPost.setEntity(new UrlEncodedFormEntity(licenses));
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.d("httpclient tag", e.getMessage());
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
Log.d("result is", result);
}catch(Exception e){
Log.d("log-tag", "Error converting result "+e.toString());
}
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.d("from jsonObject", "id= " + json_data.getInt("Id") + ", number = "
+json_data.getString("Number"));
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}