分享

PHP数组由sql行构成json_encode

 印度阿三17 2019-06-28

我无法将使用sql查询生成的php数组转换为使用json_encode的JSONObject.我使用谷歌凌空来实现连接.

当涉及单行结果时,我没有遇到任何问题,但是当有超过1行时,我在我的应用程序中得到错误,这意味着我没有真正收到JSONObject.

这是我的PHP代码

if (mysql_num_rows($result) > 0) {

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

我就是这样回来的

echo json_encode($rutina);

我知道mysql已被弃用,我很快就会迁移到mysqli.

将我的sql行数组转换为JSONObject的正确方法是什么?

编辑:

这是我等待JSONObject的android代码:

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

我正在响应错误的祝酒词.我假设它是因为我没有得到JSONObject?它仅适用于1行.

解决方法:

通常我使用这些就像要成功解析JSON对象那样需要做一些事情,页面头必须有json作为MIME类型,所以任何其他代码都可以轻松识别它.

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

它一直适用于我…不需要使用while循环,它将输出作为数据库查询找到的行的关联数组

来源:https://www./content-2-276301.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多