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.

  • 1
    Where's the other code that will show the encoded data of json? – aldrin27 Sep 14 '15 at 23:44
  • 1
    And what is that error? – Darren Sep 14 '15 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 – VolkerK Sep 14 '15 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. – Iñaki Pedroche Aramburu Sep 14 '15 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 – aldrin27 Sep 15 '15 at 00:04
  • Here's the link for you http://stackoverflow.com/questions/3408985/json-array-iteration-in-android-java – aldrin27 Sep 15 '15 at 00:12
  • @aldrin27 im kind of newbie with android and JSON son each row becomes a JSONObject inside a JSONArray? – Iñaki Pedroche Aramburu Sep 15 '15 at 00:19
  • "becomes a JSONObject inside a JSONArray" - yes. And if you want it that way (which is probably a good idea), forget my answer; don't change the structure of the repsonse but adjust the client code to expect an array of objects. – VolkerK Sep 15 '15 at 00:21
  • i think thats how i want it, because each row will become part of a listview, so i think i should change jsonObjectrequest with jsonarrayrequest right? i ll give it a try – Iñaki Pedroche Aramburu Sep 15 '15 at 00:25

1 Answers1

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

Marmik Bhatt
  • 607
  • 4
  • 16