我有这个PHP代码将我的MYSQL结果构建成JSON:
<?php
$mysql_db_hostname = "localhost";
$mysql_db_user = "root";
$mysql_db_password = "";
$mysql_db_database = "essensplan";
$con = @mysqli_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password, $mysql_db_database);
if (!$con) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
$var = array();
$sql = "SELECT * FROM beispiel";
$result = mysqli_query($con, $sql);
while($obj = mysqli_fetch_object($result)) { $var[] = $obj; }
echo '{"users":'.json_encode($var).'}';
?>
PHP脚本适用于我的Apache和PHP版本是5.5.11。
但是当我调用脚本时,只显示{users:}
并且错过了来自mysql数据库的json数据。有人有想法吗?
mysqli_set_charset($con, 'utf8');
答案 0 :(得分:1)
您应该在检查连接错误后修改该部件,如下所示:
$var = array();
$sql = "SELECT * FROM beispiel";
$result = mysqli_query($con, $sql);
while($obj = mysqli_fetch_object($result)) {
$var['users'][] = $obj;
}
echo json_encode($var);
例如,如果返回的结果是数组
array(
'name' => 'person1',
'age' => 25
),
array(
'name' => 'person2',
'age' => 30
),
array(
'name' => 'person3',
'age' => 22
)
然后您返回的JSON响应将如此:
{"user":[{"name":"person1","age":25},{"name":"person2","age":30},{"name":"person3","age":22}]}
希望解决您的问题,如果需要进行任何修改,请提供更多信息。