4

im having trouble converting an php array made from a sql query to JSONObject with json_encode. Im using google volley to achieve conection.

when it comes to a single row result, im not getting any issues, but when there are more than 1 row, im getting an error in my app which means im not really reciving a JSONObject.

here is my php code

if (mysql_num_rows($result) > 0) {

$rutina = array();
while($row = mysql_fetch_assoc($result))
{
    $rutina[] = $row;
}}  

and i return it this way

echo json_encode($rutina);

i know mysql is deprecated and im migrating to mysqli soon.

what is the correct way to convert an array of my sql rows into JSONObject?

EDIT:

Here's my android code that waits for the JSONObject:

JsonObjectRequest solicitudRutina = new JsonObjectRequest(
            Request.Method.POST, //metodo de solicitud
            linkrutina, //url, se cambia en las variables
            map,//el objeto JSON que contiene el usuario que intentaremos descargar
            new Response.Listener<JSONObject>() { //el listener de la respuesta
                @Override
                public void onResponse(JSONObject response) { // si existe respuesta aca se cacha,

                    String temp= response.optString("sinexito");//sinexito tiene el mensaje de error de no encontrar el usuario

                    if(temp.equals("")){//si la rutina existe, iniciamos descarga

                        rutinaview.setText(response.toString());
                        //obtenerRutina(response);
                    }
                    else{
                        Context context = getApplicationContext();
                        CharSequence text = "Problema al descargar la rutina, posiblemente no exita una asignada";
                        int duration = Toast.LENGTH_LONG;

                        Toast toast = Toast.makeText(context, text, duration);
                        toast.show();
                    }

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            {
                Context context = getApplicationContext();
                CharSequence text = "Error con la base de datos.";
                int duration = Toast.LENGTH_LONG;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
            }
        }
    });
    VolleyApplication.getsInstance().getmRequestQueue().add(solicitudRutina);

im getting the toast on response error. im assuming it is because im not getting a JSONObject? it works fine with 1 row only tho.

9
  • 1
    Where's the other code that will show the encoded data of json? Commented Sep 14, 2015 at 23:44
  • 1
    And what is that error? Commented Sep 14, 2015 at 23:45
  • 1
    Your code will produce a json-array (probably an array of object literals) [ {...},{...}, ...]. If you want a json-object as the topmost element you have to use keys that are unlike 0,1,2,3,... for $rutina Commented Sep 14, 2015 at 23:47
  • 1
    @aldrin27 the code is in an android app that request a JSONObject though volley ill edit my initial quetion hold on. Commented Sep 14, 2015 at 23:56
  • 1
    When you use json_encode. It will return into a json string so when it get's through your android make that json into an object Commented Sep 15, 2015 at 0:04

1 Answer 1

3

Generally I use like these as for JSON object to be parsed successfully It is required to make some things pretty clear that page header must have json as MIME type so any other code can easily recognize it.

<?php
header('Content-Type:application/json');
//Your Database query here...
$output = mysqli_fetch_all($rutina,MYSQLI_ASSOC);
echo json_encode($output);

It works for me all the time...No need to use while loop, it will give output as a associative array of the rows found by the database query

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.