0

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();
2
  • 1
    do you need the json result of the rows? Commented Apr 27, 2019 at 18:19
  • Yes, and so that multiple rows would be there Commented Apr 27, 2019 at 18:19

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.