Json read mysql column with WHERE column = $variable

I would like to achieve the following in the same session in this order:

  1. get android variable (imei)
  2. send variable to php
  3. use variable in sql
  4. send results back to android

I use the following:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_contacts);

     // 01 - first i get imei
     TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); 
     IMEI = mngr.getDeviceId();

    // 02 - then i call class to post imei to php
    new loadData().execute();

     // 03 - on php side i use "select ... where $imei ..." 

    // 04 - get the results back to android
// (yes i am aware that this method is commented out, i will explain why below)
    //accessWebService();

    }

POST:

    class loadData extends AsyncTask<String, Integer, String> {
    private StringBuilder sb;
    private ProgressDialog pr;
    private HttpResponse req;
    private InputStream is;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected String doInBackground(String... arg0) {

          ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

          String imeino = String.valueOf(IMEI);

            nameValuePairs.add(new BasicNameValuePair("imeino",imeino));

                try
                {
                HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("http://blah/contacts.php");
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost); 
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();
                    InputStreamReader ireader = new InputStreamReader(is);
                    BufferedReader bf = new BufferedReader(ireader);
                    sb = new StringBuilder();
                    String line = null;
                    while ((line = bf.readLine()) != null) {
                        sb.append(line);
                    }
                    Log.e("pass 1", "connection success ");

            }
                catch(Exception e)

            {       
                    Log.e("Error Send",e.toString());
            }
                return id;     

    }
}

GET

 private class JsonReadTask extends AsyncTask<String, Void, String> {
      @Override
      protected String doInBackground(String... params) {
       HttpClient httpclient = new DefaultHttpClient();
       HttpPost httppost = new HttpPost(params[0]);
       try {
        HttpResponse response = httpclient.execute(httppost);
        jsonResult = inputStreamToString(response.getEntity().getContent()).toString();

        System.out.println("jsonResult: "+jsonResult);
       }


       catch (ClientProtocolException e) {
        e.printStackTrace();
       } catch (IOException e) {
        e.printStackTrace();
       }
       return null;
      }

      private StringBuilder inputStreamToString(InputStream is) {
       String rLine = "";
       StringBuilder answer = new StringBuilder();
       BufferedReader rd = new BufferedReader(new InputStreamReader(is));

       try {
        while ((rLine = rd.readLine()) != null) {
         answer.append(rLine);
        }
       }

       catch (IOException e) {
        // e.printStackTrace();
        Toast.makeText(getApplicationContext(),
          "Error..." + e.toString(), Toast.LENGTH_LONG).show();
       }
       return answer;
      }

      @Override
      protected void onPostExecute(String result) {
       ListDrwaer();
      }
     }// end async task

     public void accessWebService() {
      JsonReadTask task = new JsonReadTask();
      // passes values for the urls string array
      task.execute(new String[] { "http://blah/contacts.php" });
     }

     // build hash set for list view
     public void ListDrwaer() {

      try {
       JSONObject jsonResponse = new JSONObject(jsonResult);
       JSONArray jsonMainNode = jsonResponse.optJSONArray("contact_info");

       for (int i = 0; i < jsonMainNode.length(); i++) {
        JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
        String name = jsonChildNode.optString("Name");
        String number = jsonChildNode.optString("Number");
        String username = jsonChildNode.optString("Username");
        String status = jsonChildNode.optString("Status");

        System.out.println("jsonResult: "+jsonResult);
        System.out.println("getName: "+name);
        System.out.println("getNumber: "+number);
        System.out.println("getUsername: "+username);
        System.out.println("getStatus: "+status);

       }
      } catch (JSONException e) {
          System.out.println("Json Error" +e.toString());
          Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
      }
}

PHP:

    <?php

include 'config.php';

$con=mysql_connect("$servername", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$dbname")or die("cannot select DB");

$imei = isset($_POST['imeino']) ? $_POST['imeino'] : '';
//$imei = "000000000000000";

$sql = "select * from users WHERE IMEI ='$imei'"; 
$result = mysql_query($sql);
$json = array();

if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['contact_info'][]=$row;
}
}
mysql_close($con);
echo json_encode($json); 

    $f = fopen("log.txt", "w");
    fwrite($f, print_r($json, true));
    fclose($f);  

?>  

Ok here's the story with the code:

When I just POST [ new loadData().execute() ] and not GET [ accessWebService(); ] I can read my $imei = isset($_POST['imeino']) ? $_POST['imeino'] : ''; variable as 0000000000000 but of course I cannot return back the results because accessWebService() is commented out.

HOWEVER when I uncomment accessWebService() I can get the results back to android BUT they are null because now $imei = isset($_POST['imeino']) ? $_POST['imeino'] : ''; is empty.

so to summarize:

Whenever I call the GET method I lose my POST variable!

Answers


PHP

To support both GET and POST variables in PHP you could use $_REQUEST:

$imei = isset($_REQUEST['imeino']) ? $_REQUEST['imeino'] : '';

It's also wise to check if the parameter is set and return an error if it is not:

if ( empty($imei) ) {
    echo json_encode( array( 'error' => 'Missing imeino parameter' ) );
    return;
}

And, very important, sanitize the input before you pass it to mysql. This is dangerous:

$sql = "select * from users WHERE IMEI ='$imei'"; 

because someone might call your PHP script with contacts.php?imeino=';DROP TABLE users'. See here for more information.

Btw, PHP's mysql module is deprecated; I would recommend using PDO.

Java

The GET method of accessing your API only needs a small change to pass the imeino parameter to your PHP script:

 public void accessWebService( String imei ) {
    JsonReadTask task = new JsonReadTask();     
    task.execute(new String[] { "http://blah/contacts.php?imeino=" + imei });
 }

And, you'll need to call accessWebService with the IMEI.


Need Your Help

how to add linklable after some text in richtexbox

vb.net richtextbox linklabel

I am a .net developer . I am building a desktop application. how to add LinkLabel after some text in richtexbox ?

Mesh generation of optical lens

computational-geometry triangulation

I have points cloud of two surfaces in 3D space one for the front and the other for the back of the optical lens.