• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

SQL JSON get array instead of object

Korsholm

Lurker
Hi.

i am using this code to get some info from a sql database.

I can't figure out how to return a array if there are more than one record with the same email.


Somehow i have to put the $stmt->fetch(); in a while function and then array_push it together i think.

in java then create a array and load it in to it.

Can someone help??


Regards Danni.


PHP:
Code:
if (!empty($_POST)) {

    $response = array("error" => FALSE);

    $query = "SELECT * FROM users WHERE email = :email";

    $query_params = array(
        ':email' => $_POST['email']
    );

    try {
        $stmt = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }

    catch (PDOException $ex) {
        $response["error"] = true;
        $response["message"] = "Database Error 1";
        die(json_encode($response));
    }

    $validated_info = false;
    $email = $_POST['email'];

    $row = $stmt->fetch();

        $response["error"] = false;
        $response["user"]["uid"] = $row["unique_id"];
        $response["user"]["name"] = $row["name"];
        $response["user"]["email"] = $row["email"];

        die(json_encode($response));

}

JAVA:
Code:
StringRequest strReq = new StringRequest(Request.Method.POST,
                Functions.LOGIN_URL, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response);
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // Check for error node in json
                    if (!error) {
                        // user successfully logged in
                        JSONObject json_user = jObj.getJSONObject("user");

                    } 
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {

        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to php
                Map<String, String> params = new HashMap<String, String>();
                params.put("email", email);

                return params;
            }

        };
 
Back
Top Bottom