dstm2014 2015-11-28 12:57
浏览 43
已采纳

Json使用WHERE column = $ variable读取mysql列

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!

  • 写回答

1条回答 默认 最新

  • dsijovl015728613 2015-11-28 16:01
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能