我正在为我的 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'中获取所有数据
但是,如果我想使用不同的查询,例如“从用户名 = '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());
}