【发布时间】:2023-04-01 13:57:01
【问题描述】:
我正在尝试将 json 数据从 android 发布到 php 并运行带有值的 sql 查询,但我无法正确理解,我的想法是从 android 设备获取值,将该值发布到 php 并运行 sql 查询然后该值将数据从 sql 返回到 android。
安卓代码:
try {
JSONObject toSend = new JSONObject();
toSend.put("msg", "55555");
JSONTransmitter transmitter = new JSONTransmitter();
transmitter.execute(new JSONObject[] {toSend});
} catch (JSONException e) {
e.printStackTrace();
}
public class JSONTransmitter extends AsyncTask<JSONObject, JSONObject, JSONObject> {
String url = "http://site/file.php";
@Override
protected JSONObject doInBackground(JSONObject... data) {
JSONObject json = data[0];
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
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;
}
}
php代码:
<?php
//include 'config.php';
if( isset($_POST["json"]) ) {
$value = $_POST["json"];
$sql = "SELECT * from table WHERE Code = '".$value."'";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['myarray'][]=$row;
}
}else{
}
}
mysql_close($con);
echo json_encode($json);
?>
返回的$值是
'{"msg":"55555"}'
我希望它返回:
55555
【问题讨论】: