发布Json值从Android到服务器并使用SQL将数据返回到Android

时间:2015-11-27 17:12:03

标签: java php android json

我正在尝试将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

2 个答案:

答案 0 :(得分:0)

在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 ,因此必须先解码。

答案 1 :(得分:0)

你需要在php脚本或android(java)上解析JSON。因为您正在接收JSON格式的代码。