[英]Post Json value From Android To Server And Use SQL To Return Data Back To Android
我正在嘗試將json數據從android發布到php並使用值運行sql查詢,但我做不到,我的想法是從android設備獲取值,將該值發布到php並使用該值運行sql查詢,然后將sql中的數據返回給android。
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);
?>
返回的$ value是
'{"msg":"55555"}'
我希望它返回:
55555
在您的PHP腳本中,更改
$value = $_POST["json"];
$sql = "SELECT * from table WHERE Code = '".$value."'";
至
$value = $_POST["json"];
$decoded_value = json_decode($value);
$sql = "SELECT * from table WHERE Code = '".$decoded_value->{'msg'}."'";
由於您正在接收JSON ,因此必須首先對其進行解碼。
您需要在php腳本或android(java)上解析JSON。 由於您正在接收JSON格式的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.