PHP MySQL选择并作为json回显

时间:2019-04-27 18:16:06

标签: php mysql json

我如何回显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();

1 个答案:

答案 0 :(得分:1)

首先将所有行添加到一个数组:

$data = [];

while($row = $result->fetch_assoc()) {
    $data[] = $row;
}

然后将数组转换为json并输出:

echo json_encode($data);