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