我有这段代码试图从sql数据库创建一个json文件。该代码会打印出FINE,但会给出警告
警告:从第5行的C:\ xampp \ htdocs \ z \ index.php中的空值创建默认对象
可以为我修复任何错误。这是我的代码。
<?php include '../config.php';
$sth = mysqli_query($conn,"SELECT * from movies limit 4");
while($r = mysqli_fetch_assoc($sth)) {
$rows->id = $r['id'];
$rows->hidy = $r['hidy'];
}
print json_encode($rows);
答案 0 :(得分:1)
您需要为存在的属性创建一个新类。简单的方法是使用strClass()。
同样,如果您处于可能包含4个结果行的循环中,则循环需要将数据保存在数组中,否则您将丢失结果1,2,3,而结果4仅显示在JSON中
<?php
include '../config.php';
$sth = mysqli_query($conn,"SELECT * from movies limit 4");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$obj = new stdClass(); // new line
$obj->id = $r['id'];
$obj->hidy = $r['hidy'];
// you are in a loop of 4 results, so need an array of results
$rows[] = $obj;
}
echo json_encode($rows);
或者,仅选择要使用的列并将结果作为对象->fetch_object()
<?php
include '../config.php';
$sth = mysqli_query($conn,"SELECT id,hidy from movies limit 4");
$rows = array();
while($r = $sth->fetch_object()) {
$rows[] = $r;
}
echo json_encode($rows);