duanhai4046 2015-11-27 09:12 采纳率: 100%
浏览 73
已采纳

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

I am trying to post json data from android to php and run sql query with value but I can't get it right, the idea is to get value from android device, post that value to php and run an sql query with that value then return the data from sql back to android.

android code:

        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 code:

    <?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 returned is

'{"msg":"55555"}'

I would like it to return:

55555

展开全部

  • 写回答

2条回答 默认 最新

  • dongliao6491 2015-11-27 09:16
    关注

    In your PHP script, change

    $value = $_POST["json"]; 
    $sql = "SELECT * from table WHERE Code = '".$value."'";
    

    to

    $value = $_POST["json"]; 
    $decoded_value = json_decode($value);
    $sql = "SELECT * from table WHERE Code = '".$decoded_value->{'msg'}."'";
    

    Since you are receiving JSON, you must decode it first.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部