mvasco
mvasco

Reputation: 5101

Sending request with params to PHP file

I am working on an Android app. There is a fragment with a ListView. I am populating the ListView with JSON data received from a PHP file on a remote server.

This is the code:

 private void getJSON(){
        class GetJSON extends AsyncTask<Void,Void,String> {

            ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(getActivity(),"Fetching Data","Wait...",false,false);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                JSON_STRING = s;
                showEmployee();
            }

            @Override
            protected String doInBackground(Void... params) {
                RequestHandler rh = new RequestHandler();
                String s = rh.sendGetRequest(Config.URL_GET_ALL);
                Log.d("URL", "URL_GET_ALL: " + s );
                return s;
            }
        }
        GetJSON gj = new GetJSON();
        gj.execute();
    }

And this is the remote PHP file:

<?php 
    //Importing Database Script 
    require_once('dbConnect.php');


    //Creating sql query
    $sql = "SELECT * FROM tb_direcciones";

    //getting result 
    $r = mysqli_query($con,$sql);

    //creating a blank array 
    $result = array();

    //looping through all the records fetched
    while($row = mysqli_fetch_array($r)){

        //Pushing name and id in the blank array created 
        array_push($result,array(
            "id_address"=>$row['id_address'],
            "cia"=>$row['cia'],
            "fn"=>$row['fn'],
            "ln"=>$row['ln'],
            "ad1"=>$row['ad1'],
            "ad2"=>$row['ad2'],
            "type"=>$row['type'],
            "city"=>$row['city'],
            "state"=>$row['state'],
            "zip"=>$row['zip'],
            "phone"=>$row['phone'],
            "ext"=>$row['ext'],
            "fromto"=>$row['fromto'],
            "user"=>$row['user']

        ));
    }

    //Displaying the array in json format 
    echo json_encode(array('result'=>$result));

    mysqli_close($con);
    ?>

This part is working fine.

Now I want to filter the rows from the database table. There is a String variable called MyId in the fragment. I need to filter the rows where field user is equal to MyId.

How should I change the request to pass MyId as param to the PHP file?

EDITED

RequestHandler class:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

public class RequestHandler {

    //Method to send httpPostRequest
    //This method is taking two arguments
    //First argument is the URL of the script to which we will send the request
    //Other is an HashMap with name value pairs containing the data to be send with the request
    public String sendPostRequest(String requestURL,
                                  HashMap<String, String> postDataParams) {
        //Creating a URL
        URL url;

        //StringBuilder object to store the message retrieved from the server
        StringBuilder sb = new StringBuilder();
        try {
            //Initializing Url
            url = new URL(requestURL);

            //Creating an httmlurl connection
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            //Configuring connection properties
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            //Creating an output stream
            OutputStream os = conn.getOutputStream();

            //Writing parameters to the request
            //We are using a method getPostDataString which is defined below
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            int responseCode = conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {

                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                sb = new StringBuilder();
                String response;
                //Reading server response
                while ((response = br.readLine()) != null){
                    sb.append(response);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public String sendGetRequest(String requestURL){
        StringBuilder sb =new StringBuilder();
        try {
            URL url = new URL(requestURL);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String s;
            while((s=bufferedReader.readLine())!=null){
                sb.append(s+"\n");
            }
        }catch(Exception e){
        }
        return sb.toString();
    }

    public String sendGetRequestParam(String requestURL, String id){
        StringBuilder sb =new StringBuilder();
        try {
            URL url = new URL(requestURL+id);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String s;
            while((s=bufferedReader.readLine())!=null){
                sb.append(s+"\n");
            }
        }catch(Exception e){
        }
        return sb.toString();
    }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }

Upvotes: 0

Views: 185

Answers (2)

Indra Kumar S
Indra Kumar S

Reputation: 2935

You may use post method

       @Override
        protected String doInBackground(Void... params) {

            HashMap<String, String> postDataParams = new HashMap<String,String>();
            postDataParams.put("MyId", someIdHere);
            postDataParams.put("SomeOtherID", someOtherHere);
            RequestHandler rh = new RequestHandler();
            String result = rh.sendPostRequest(Config.URL_GET_ALL,postDataParams);
             Log.d("URL", "URL_GET_ALL_FILTERED: " + result );
            return result;
        }

And in PHP part, You need to sanitize the user input. If it is a an integer you can use

    $given_id = intval($REQUEST["MyId"]);

as stated by Todor. If it is a string ,you need to use prepared statements to avoid SQL Injections

Upvotes: 1

Todor Simeonov
Todor Simeonov

Reputation: 806

You sholud pass the user ID as a parameter to the query. You can pass it as a GET parameter or as a POST parameter. The following example is for GET, which is OK when the value is integer.

Android App Code:

        @Override
        protected String doInBackground(Void... params) {
            RequestHandler rh = new RequestHandler();
            String s = rh.sendGetRequest(String.format("%s&myid=&d", Config.URL_GET_ALL, (int)myID) );
            Log.d("URL", "URL_GET_ALL: " + s );
            return s;
        }

PHP code:

//Creating sql query
$sql = "SELECT * FROM tb_direcciones WHERE user = '".intval($_GET['myid'])."' ";

Consider adding some security (authentication) to your web service (PHP code). It seem like it will pass too much personal information and if it works on a pulbic netowork anyone can easily receive your stored data.

Upvotes: 1

Related Questions