PHP array made of sql rows to json_encode

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.

Upvotes: 4

Views: 439

Answers (1)

Marmik Bhatt
Marmik Bhatt

Reputation: 607

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

Upvotes: 3

Related Questions