PHP JSON结果多个空

时间:2014-12-29 12:14:53

标签: php mysql json

我开发了一个带有Mysql数据库的android应用程序。我想我的SQL查询的结果显示在表中的JSON变量中。如果我使用TableA“country”的单列---> “id_country”或“name_en_country”它可以工作,但如果我想显示更多列---> “id_country”和“name_en_country”等等......结果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();

?>

1 个答案:

答案 0 :(得分:0)

根据此处设置的示例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();
?>