我用Mysql数据库开发了一个Android应用程序。我希望我的 sql 查询结果显示在表中的 JSON 变量中。如果我使用我的 TableA"国家"的单列--->"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();
?>
根据这里设置的示例 mySQL for calendar while 循环中的 json_encode() 数组,您的代码应该像这样更改:
<?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();
?>