我正在尝试从mySQL检索数据并生成JSON文件 但输出只显示了一行 数据库表中有很多行 这段代码有什么问题?
$sql = "SELECT * FROM form_element";
$result = mysqli_query($conn, $sql);
$response = array();
$data_array = array();
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($data = mysqli_fetch_assoc($result)) {
$id = $data['id'];
$name = $data['name'];
$email = $data['email'];
$phone = $data['phone'];
$address = $data['address'];
$data_array = array(
'name' => $name,
'email' => $email,
'phone' => $phone,
'address' => $address
);
}
} else {
echo "0 results";
}
$response['data_array'] = $data_array;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
答案 0 :(得分:3)
每次循环时你都会覆盖$data_array
。
所以,这部分:
$data_array = array(
'name' => $name,
'email' => $email,
'phone' => $phone,
'address' => $address
);
应更改为:
$data_array[] = array(
'name' => $name,
'email' => $email,
'phone' => $phone,
'address' => $address
);
然后每行都添加到$data_array
。