0

I am trying to get user_details from mysql to my android applicaion. For this I am posting data from android and getting the values by $_POST['mobile'] and $_POST['usertype'] method in my php page. To check if data is posting or not I have tried an insert statement first by below

//this works 

$mobile = $_POST['mobile'];
$usertype = $_POST['usertype'];
sql = "INSERT INTO etc(id, etc) VALUES('$mobile', '$usertype')"

and it is working fine that means my post method is sending data. But when I am trying to read data by using the posted value in where statement below it is not returing any data to my application

// this doesn't work

$mobile = $_POST['mobile'];
$usertype = $_POST['usertype'];
$sql = "SELECT * FROM users where mobile_number='$mobile' and user_type='$usertype'";

Again if I hardcoded the two variable like below and use the same it is returning data to my application

//this returning data to my application

$mobile = 1812043433;
$usertype = Driver;
$sql = "SELECT * FROM users where mobile_number='$mobile' and user_type='$usertype'";

what's wrong am i doing here

This is my php page

  $mobile = $_POST['mobile'];
  $usertype = $_POST['usertype'];

  // Create connection
  $con=mysqli_connect("**","***","**","**");

  // Check connection
 if (mysqli_connect_errno())
 {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }

 $sql = "SELECT * FROM users where mobile_number='$mobile' and user_type='$usertype'";

  if ($result = mysqli_query($con, $sql))
   {
   $resultArray = array();
   $tempArray = array();

   while($row = $result->fetch_object())
   {
   // Add each result into the results array
   $tempArray = $row;
   array_push($resultArray, $tempArray);
   }
   echo json_encode($resultArray);
   }
   // Close connections
   mysqli_close($con);

and this is my android where i am parsing

private void downloadJSON(final String urlWebService) {

    class DownloadJSON extends AsyncTask<Void, Void, String> {

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


        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            // Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
            // Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).setText("Posting Bid");

            try {
                loadIntoListView(s);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected String doInBackground(Void... voids) {
            try {
                URL url = new URL(urlWebService);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                StringBuilder sb = new StringBuilder();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String json;
                while ((json = bufferedReader.readLine()) != null) {
                    sb.append(json + "\n");
                }
                return sb.toString().trim();
            } catch (Exception e) {
                return null;
            }
        }
    }
    DownloadJSON getJSON = new DownloadJSON();
    getJSON.execute();
}

private void loadIntoListView(String json) throws JSONException {

    JSONArray jsonArray = new JSONArray(json);
    String[] stocks = new String[jsonArray.length()];
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject obj = jsonArray.getJSONObject(i);

        //stocks[i] = obj.getString("name") + " " + obj.getString("price");
        String driverid=stocks[i] = obj.getString("id");
        String driverfname=stocks[i] = obj.getString("first_name");
        String driverlname=stocks[i] = obj.getString("last_name");
        String driveravator="url";
        String driverratings="3.8";

        /*
        tvhiddendriverId.setText(driverid);
        tvhiddendriverfName.setText(driverfname);
        tvhiddendriverlName.setText(driverlname);
        tvhiddendriverAvator.setText(driveravator);
        tvhiddendriverRatings.setText(driverratings);*/

        /*Inserting to SQLITE directly from here

        this.deleteDatabase("ContactsDB"); 

        ContactsDB db=new ContactsDB(this);
        db.open();
        db.createEntry(driverid,driverfname,driverlname,driveravator,driverratings);
        db.close();
        Toast.makeText(this, "saved to db", Toast.LENGTH_SHORT).show();

     }
}
Mithu
  • 665
  • 1
  • 8
  • 38
  • 1
    Can you share us the android code where you are trying to parse this? – Vinay Jayaram Dec 02 '19 at 08:30
  • I have added the code – Mithu Dec 02 '19 at 08:39
  • What are you sending in urlWebService, I need this part of information to make sure you are sending the data properly – Vinay Jayaram Dec 02 '19 at 08:43
  • in url it is sending data in json format. all is working perfect except when i use the post variable in my sql query – Mithu Dec 02 '19 at 08:45
  • this are the data sending when i hardcoded the two variable but[{"id":"10002","first_name":"sala","last_name":"uddin","email":"jobs3433@gmail.com","country_code":"880","mobile_number":"1812043433","password":"$2y$10$rdrucafqXRH1OJ.z9eViN.VhSMHA\/QZqbvGiV.nbGp17F98mOz7Tq","user_type":"Driver","remember_token":null,"fb_id":null,"google_id":null,"status":"Active","device_type":null,"device_id":"","payout_id":"JOBS3433@GMAIL.COM","created_at":"2019-11-22 11:02:49","updated_at":"2019-12-02 08:08:36","deleted_at":null}] – Mithu Dec 02 '19 at 08:46
  • if you ECHO $mobile = $_POST['mobile']; $usertype = $_POST['usertype']; are you getting the values you are sending from android? – Vinay Jayaram Dec 02 '19 at 08:46
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/203451/discussion-between-vinay-jayaram-and-mithu). – Vinay Jayaram Dec 02 '19 at 08:47
  • i have not tried with echo but As i insert data from $_POST['mobile']; and $_POST['usertype']; it is inserting posted data that means I am getting the values – Mithu Dec 02 '19 at 08:48
  • What I've got from the question, is that you want to send some data to your server and then retrieve them back to your application in another request. Is that correct? – Mohammad Zarei Dec 02 '19 at 08:53
  • yes exactly same – Mithu Dec 02 '19 at 08:58
  • @Mithu Did you check my answer? – Mohammad Zarei Dec 03 '19 at 06:49
  • it works for the insert statement but not for the retreive data – Mithu Dec 03 '19 at 07:09

1 Answers1

0

Well....we have 2 parts here. An API to insert data into our database:

 <?php
 $mobile = $_GET['mobile'];
 $usertype = $_GET['usertype'];

  // Create connection
  $con=mysqli_connect("localhost","root","","test");

  // Check connection
 if (mysqli_connect_errno())
 {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }

 $sql = "INSERT into users (mobile_number, user_type) VALUES ('$mobile','$usertype')";

 if ($con->query($sql) === TRUE) {
     echo "New record created";
 } else {
     echo "Error: ";
 }

 $con->close();
?>

And another API to retrieve data back to us:

<?php
 $mobile = $_GET['mobile'];
 $usertype = $_GET['usertype'];

  // Create connection
  $con=mysqli_connect("localhost","root","","test");

  // Check connection
 if (mysqli_connect_errno())
 {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }

 $sql = "SELECT * FROM users where mobile_number='$mobile' and user_type='$usertype'";

  if ($result = mysqli_query($con, $sql))
   {
   $resultArray = array();
   $tempArray = array();

   while($row = $result->fetch_object())
   {
   // Add each result into the results array
   $tempArray = $row;
   array_push($resultArray, $tempArray);
   }
   echo json_encode($resultArray);
   }
   // Close connections
   mysqli_close($con);

?>

Well, we've done the API part. Now we need to get the android part done. To insert user in your database, first you need to add Volley to your program:

dependencies {
    ...
    implementation 'com.android.volley:volley:1.1.1'
}

And to use Volley, you must add the android.permission.INTERNET permission to your app's manifest. Without this, your app won't be able to connect to the network.

RequestQueue queue = Volley.newRequestQueue(this);
String url ="YOUR_TARGET_URL";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
         //get your response and parse it with Gson
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        // Something went wrong
    }
});

// Add the request to the RequestQueue.
queue.add(stringRequest);
Mohammad Zarei
  • 1,773
  • 14
  • 33