我在一个android应用程序上工作,它应该向服务器上的php代码发送查询参数,php代码应该检索结果并将其显示给用户。
所以我需要一个php代码来完成这个任务。
JSONTransmitter
public class JSONTransmitter extends AsyncTask<JSONObject, JSONObject, JSONObject> {
String url = " /..../Three.php";
protected JSONObject doInBackground(JSONObject... data) {
JSONObject json = data[0];
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
JSONObject jsonResponse = null;
HttpPost post = new HttpPost(url);
try {
StringEntity se = new StringEntity("json="+json.toString());
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(se);
HttpResponse response;
response = client.execute(post);
String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
jsonResponse=new JSONObject(resFromServer);
Log.i("Response from server", jsonResponse.getString("msg"));
} catch (Exception e) { e.printStackTrace();}
return jsonResponse;
}
}MainActivity
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
JSONObject toSend = new JSONObject();
toSend.put("msg", 1);
JSONTransmitter transmitter = new JSONTransmitter();
transmitter.execute(new JSONObject[] {toSend});
} catch (JSONException e) {
e.printStackTrace();
}
}
} 这是我的php代码试用版
<?php
if( isset($_POST["json"]) ) {
$data = json_decode($_POST["json"]);
mysql_connect("localhost", "root", "password")
or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$data = mysql_query(" select part_name from Services_parts where part_id= $data->msg ")
or die(mysql_error());
echo json_encode($data);
}
?>发布于 2015-12-28 19:48:13
首先,不要使用旧的mysql_...函数。我推荐你使用PDO,但如果你想要“老式的MySQL风格”,至少要使用MySQLi。另外,由于我假设您不熟悉安全过程,因此请阅读SQL注入。
但让我们来解决您的问题:)
您需要从查询中获取结果,并将其传递给mysql_fetch_row或其他fetch函数之一。
$result = mysql_query("select...");
echo json_encode(mysql_fetch_row($result));发布于 2016-01-04 19:35:05
如果你什么都没有得到,那就是你没有正确地发送数据。尝试记录您的数据JSONObject json = data[0];,看看您得到了什么。乍一看,你的php看起来很好。当你测试你的代码时,把它分解成更小的部分。如果你认为你的php是错误的,那么在php代码上面创建一个带有输入和按钮的html表单,然后试一试。如果它能工作,那就没问题了。但这里你的问题出在安卓上。记录你的数据,看看是怎么回事。我不熟悉JSONTransmiter,我从来没有用过它,但这里有一个例子,它帮助我实现了外部基础通信。http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/。这是一个干净而简单的完美例子。
https://stackoverflow.com/questions/34490191
复制相似问题