【问题标题】:Post Json value From Android To Server And Use SQL To Return Data Back To Android将 Json 值从 Android 发送到服务器并使用 SQL 将数据返回到 Android
【发布时间】: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

【问题讨论】:

    标签: java php android json


    【解决方案1】:

    在您的 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,因此您必须先对其进行解码。

    【讨论】:

      【解决方案2】:

      您需要在 php 脚本或 android(java) 上解析 JSON。由于您收到的是 JSON 格式的代码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-19
        • 2015-08-21
        • 2013-10-01
        相关资源
        最近更新 更多