我如何回显mysql select作为json的结果? 当前它将回显响应:
ID: 1 - Name: John Doe
ID: 2 - Name: John Deo
最诚挚的问候,
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
答案 0 :(得分:1)
首先将所有行添加到一个数组:
$data = [];
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
然后将数组转换为json并输出:
echo json_encode($data);