I work on an android app that should send a query parameter to a php code on server and the php code should retrieves the result and shows it for the user
So I need to a php code for this task.
JSONTransmitter
public class JSONTransmitter extends AsyncTask<JSONObject, JSONObject, JSONObject> {
String url = " /..../Three.php";
protected JSONObject doInBackground(JSONObject... data) {
JSONObject json = data[0];
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
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;
}
}
MainActivity
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
JSONObject toSend = new JSONObject();
toSend.put("msg", 1);
JSONTransmitter transmitter = new JSONTransmitter();
transmitter.execute(new JSONObject[] {toSend});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This my php code trial
<?php
if( isset($_POST["json"]) ) {
$data = json_decode($_POST["json"]);
mysql_connect("localhost", "root", "password")
or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$data = mysql_query(" select part_name from Services_parts where part_id= $data->msg ")
or die(mysql_error());
echo json_encode($data);
}
?>