gpt4 book ai didi

java - 使用 java (android) 在 php 中动态更改 mysql 查询

转载 作者:可可西里 更新时间:2023-11-01 08:52:23 27 4
gpt4 key购买 nike

我正在为我的 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”中获取所有数据

但是如果我想使用不同的查询,例如“从某个表中选择前 1 个,其中用户名 = 'thisuser'”。我怎样才能在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());
}

最佳答案

为什么不尝试向请求中添加参数?

例如:

http://some-url.com/getAllDataFromSomeTable.php?table=difftable&whereField.1=username&whereValue.1=xyz&whereField.2=surname&whereValue.2=Smith

这样您就需要解析这些参数并根据传递的数据构建查询。我认为上述请求会进行以下查询:

select * from difftable where username = 'xyz' and surname ='Smith'

另一方面,这就是网络服务的用途,所以如果可能的话,我会考虑类似的事情。

关于java - 使用 java (android) 在 php 中动态更改 mysql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11461304/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com