Android Volley: Select data from a MySQL database using an identifier specified by the user.

I am writing a simple Android application using Volley . I would like to know how to select the first and last name from the MySQL database by identifier , which the user enters into editText in the application . This is my PHP script:

 <?php
    include 'connection.php';

    global $connect;
    $id = $_POST["id"];

    $query = "SELECT firstName, lastName FROM users WHERE id = '$id'";

    $result = mysqli_query($connect, $query);
    $number_of_rows = mysqli_num_rows($result);

    $response = array();

    if($number_of_rows > 0) {
        while($row = mysqli_fetch_assoc($result)) {
            $response[] = $row;
        }
    }

    header('Content-Type: application/json');
    echo json_encode(array("users"=>$response));
    mysqli_close($connect);

?>

If I specified an ID in the code, it returns the data in the JSON that I require, so the script and database are fine. The answer I get for $ id = 1:

{"users":[{"firstName":"Jonash","lastName":"Corvin"}]}

And this is my StringRequest code:

    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        try {
            JSONArray jsonArray = new JSONArray(response);
            JSONObject jsonObject = jsonArray.getJSONObject(0);

            String firstName = jsonObject.getString("firstName");
            String lastName = jsonObject.getString("lastName");

            firstNameTV.setText(firstName);
            lastNameTV.setText(lastName);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Toast.makeText(MainActivity.this, "Something went wrong",Toast.LENGTH_LONG).show();
        error.printStackTrace();
    }
}) {
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String,String> parameters = new HashMap<String, String>();
        parameters.put("id", idEditText.getText().toString());
        return parameters;
    }
    };
queue.add(stringRequest);

Unfortunately, he is not doing anything ... He is not even showing an error message or toast. Do you know how to fix this?

+4
1

{ "": [{ "FirstName": "Jonash", "LastName": "" }]}

JSON JSON :

JSONObject jsonobject = new JSONObject(response);
JSONArray jsonarray = jsonobject.getJSONArray("users");
JSONObject data = jsonArray.getJSONObject(0);

String firstName = data.getString("firstName");
String lastName = data.getString("lastName");
+4

Source: https://habr.com/ru/post/1676521/


All Articles