userxöa
userxöa

Reputation: 63

PHP MySQL select and echo as json

How could I echo the result of mysql select as json? Currently it will echo response:

ID: 1 - Name: John Doe
ID: 2 - Name: John Deo

Best regards,

$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();

Upvotes: 0

Views: 326

Answers (1)

HTMHell
HTMHell

Reputation: 6006

First add all rows to one array:

$data = [];

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

Then convert the array to json and output:

echo json_encode($data);

Upvotes: 1

Related Questions