【问题标题】:PHP JSON result multiple emptyPHP JSON 结果多个空
【发布时间】:2014-12-29 12:14:53
【问题描述】:

我用 Mysql 数据库开发了一个安卓应用程序。我希望我的 sql 查询结果显示在表中的 JSON 变量中。如果我使用 TableA “country” ---> “id_country” 或 “name_en_country” 的单列,它可以工作,但如果我想显示更多列 ---> “id_country” AND “name_en_country” AND 更多...... . 结果 Requet php 给我发了一个空白页。你能帮我吗,谢谢!

<?php

// Create Database connection
$mysqli = new mysqli("localhost", "root", "", "whenmeeat");
if (!$mysqli) {
    printf("Échec de la connexion : %s\n", mysqli_connect_error());
}

// Replace * in the query with the column names.
$result = $mysqli->query("select id_country, name_en_country, name_fr_country from country", MYSQLI_USE_RESULT);

// Create an array
$json_response["country"] = array();

while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
    $row_array['id_country'] = $row['id_country'];
    $row_array['name_en_country'] = $row['name_en_country'];

    // push the values in the array
    array_push($json_response["country"],$row_array);
}
echo json_encode($json_response["country"]);

// Close the database connection
$mysqli->close();

?>

【问题讨论】:

  • 空白页通常意味着你没有配置 PHP 来显示错误信息。你需要先解决这个问题,而不是一直猜测。
  • 如果我有 php 错误,我会出现一个错误页面。我已经尝试过了。
  • 那么你可能只是得到NULL。您可以使用var_dump(json_encode(...)) 进行验证,并且(如果是这种情况)您可以使用json_last_error() 看到错误。我的印象是您没有使用正确的 UTF-8 提供 JSON 函数。

标签: php mysql json


【解决方案1】:

根据此处设置的示例json_encode() array in while loop for mySQL for calendar,您的代码应更改如下:

<?php
// Create Database connection
$mysqli = new mysqli("localhost", "root", "", "whenmeeat");
if (!$mysqli) {
    printf("Échec de la connexion : %s\n", mysqli_connect_error());
}

// Replace * in the query with the column names.
$stmt = $mysqli->prepare("SELECT `id_country`, `name_en_country`, `name_fr_country` FROM `country`");
$stmt->execute();
$res = $stmt->get_result(); 
// Create an array
$json = array();
while ($row = $res->fetch_assoc()) {
            $country = array(
                        'id_country' => $row['id_country'],
                        'name_en_country' => $row['name_en_country'],
                        'name_fr_country' => $row['name_fr_country']
                    );
            $json[] = $country ;
}
echo json_encode($json);
// Close the database connection
$mysqli->close();
?>

【讨论】:

  • 你好,我尝试了你的代码,如果我放一列来显示它,结果是一样的,但是如果我放更多列,我有一个空白页。
  • 是的,我试试。你和截图?如果你愿意,我可以
  • 我想你现在不会有问题了。
  • 对不起,它不起作用,同样的问题。天哪,我不明白为什么,当我删除 2 行 "'name_en_country' => $row['name_en_country'], 'name_fr_country' => $row['name_fr_country'] " 时它的工作。
  • 请检查您的餐桌设置。在我的本地主机示例中,我得到了这个结果。 [{"id_country":2,"name_en_country":"USA","name_fr_country":"USA"},{"id_country":3,"name_en_country":"Greece","name_fr_country":"Grece"}]
猜你喜欢
  • 2011-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
相关资源
最近更新 更多