无法从JSON - PHPMyAdmin接收数据

时间:2017-06-22 11:15:11

标签: php android mysql json phpmyadmin

我有一个PHP脚本,用于从BBDD获取一些信息:

<?php 
//Creating a connection
$con = mysqli_connect("localhost:3306","root","","database");

if (mysqli_connect_errno())
{
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql= "SELECT * FROM tQuestions";

$result = mysqli_query($con ,$sql);

while ($row = mysqli_fetch_assoc($result)) 
{       
    $array[] = $row;
    (ONLY USED ON SECOND TRY) echo $row;
}
header('Content-Type:Application/json');

echo json_encode($array);

mysqli_free_result($result);

mysqli_close($con);
?>

当我在Android App上使用它时,我收到一个空值。此外,当我转到正确的链接时,我收到一个没有信息的页面和一个无效的JSON文件。

当我放一个echo $row来查看我收到的内容时,我有一个这样的字符串:ArrayArrayArrayArray,它有50个“数组”字,与我所拥有的字相同数据库。

我做错了什么?

这是我的Android代码:

private void getQuestionsFromDB() {

    AsyncTask<Void, Void, JSONArray> asyncTask = new AsyncTask<Void, Void, JSONArray>() {
        @Override
        protected JSONArray doInBackground(Void... params) {

            JSONArray array = null;
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("http://www.am-motion.eu/scriptsapp/preguntas.php")
                    .build();
            try {
                Response response = client.newCall(request).execute();

                array = new JSONArray(response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return array;
        }

        @Override
        protected void onPostExecute(JSONArray array) {
            try {
                for (int i = 0; i < array.length(); i++) {
                    JSONObject object = null;
                    object = array.getJSONObject(i);

                    listQuestions.add(object.getString("Question"));

                    listAnswers.add(object.getString("Answer1"));
                    listAnswers.add(object.getString("Answer2"));
                    listAnswers.add(object.getString("Answer3"));
                    listAnswers.add(object.getString("Answer4"));

                    listCorrectAnswer.add(object.getString("Answer"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    asyncTask.execute();
}

1 个答案:

答案 0 :(得分:0)

您的问题是您将所有数组传递给'json_encode'函数。您必须使用for或foreach循环来解析值:

for ($i = 0; $i < sizeof($array); $i++) {
    echo json_encode($array[$i]);
}

如果你想要一个JSONArray,你可以使用:

for ($i = 0; $i < sizeof($array); $i++) {
    if($i==0){
        echo '[';
        echo json_encode($array[$i]);
    } else if ($i == sizeof($array) -1) {
        echo json_encode($array[$i]);
        echo "]";
    } else {
        echo json_encode($array[$i]);
        echo ",";
    }
}