Android Volley: select data from MySQL database by id specified by user


I’m writing a simple Android application using Volley. I’d like to know how to select a first name and a last name from MySQL database by ID, which user enter into editText in application. This is my PHP script:

    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));


If I specified the ID in the code, it returns a data in JSON, which I demand, so the script and the database are ok. The response which I get for $id=1 is:


And this is my code of StringRequest:

    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
    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");


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

Unfortunately, it doesn’t do anything… It even doesn’t show any error or toast message. Do you know how to fix it?



According to the given JSON you need to parse the JSON like this:

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");

Answered By – jagapathi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published