2

I created a mySQL database with phpMyAdmin in my local server. In this database I stored the names and the location of my friends (along with an id as a primary key for the database). I wrote and run the following php script to retrieve these data from the database and project them on my local web server (XAMPP):

<?php

$dbServername = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'Friends';

$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);

header('Content-Type: application/json');

$sql = 'SELECT * FROM friends;';
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);

if ($resultCheck > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo json_encode($row, JSON_PRETTY_PRINT);

    }
}

However, in this way I take this output:

{
    "id": "1",
    "name": "David Belton",
    "location": "New Haven"
}{
    "id": "2",
    "name": "Alex Danson",
    "location": "New York"
}

which is not a valid json output overall. I would like to have the following output:

[{
        "id": "1",
        "name": "David Belton",
        "location": "New Haven"
    }, {
        "id": "2",
        "name": "Alex Danson",
        "location": "New York"
  }]

(which is also a valid json output)

How can I do this?

4 Answers 4

1

This is happening because you're echoing out each object in isolation from the others, inside your loop.

while ($row = mysqli_fetch_assoc($result))
    echo json_encode($row, JSON_PRETTY_PRINT); //<-- echo out an isolated JSON object

Instead, just store everything in an array until you're done then echo out the JSON once, not iteratively.

$arr = [];
while ($row = mysqli_fetch_assoc($result)) $arr[] = $row;
json_encode($arr, JSON_PRETTY_PRINT);
Sign up to request clarification or add additional context in comments.

3 Comments

Surely the result of mysqli_fetch_assoc($result) would be the same as $arr so possibly an easier solution is to simply json_encode(mysqli_fetch_assoc($result), JSON_PRETTY_PRINT); ? But +1 for explanation.
The point is to store the retrieved associative arrays in an outer array, then JSON encode that outer array. That produces the output the OP wants.
Thank you for your response. Perhaps I would like it a bit less dense but it is the right one so it's ok.
1

Store the result in the array, then echo the encoded/formatted array:

<?php

$dbServername = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'Friends';

$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);

header('Content-Type: application/json');

$sql = 'SELECT * FROM friends;';
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);

$arr = array();

if ($resultCheck > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        array_push($arr, $row);
    }
}

echo json_encode($arr, JSON_PRETTY_PRINT);

Comments

1

Or, instead of fetching results one-by-one, just use mysqli_fetch_all

if ($resultCheck > 0)
{
    $row = mysqli_fetch_all($result);
    echo json_encode($row, JSON_PRETTY_PRINT);
}

which is actually faster and uses less memory: http://php.net/manual/en/mysqli-result.fetch-all.php

3 Comments

This is pretty cool(upvote). However keep in mind that this returns an array of arrays and not a simple array.
Thanks! You're right, this is an array of arrays but in your accepted answer, $arr is also an array of arrays
Haha, I did not realise this even if tested it...also I used finally the second answer...
1

Create an array and push those records in while loop. At the end echo json_encode(); so the output will be in proper JSON format

$records = array();
if ($resultCheck > 0) {
    while ($row = mysqli_fetch_assoc($result)) {

        $records[] = $row;
    }
}
echo json_encode($records, JSON_PRETTY_PRINT);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.