Jordan Osterberg
Jordan Osterberg

Reputation: 43

PHP json_encode with array only returns first element?

I'm attempting to encode some values in JSON, so I can use them within other applications and also create a web API for them. to access them. I have this SQL method to grab data from my database:

function getAllMessages() {
    return getConnection()->query("SELECT * FROM allMessages ORDER BY programTimestamp DESC");
}

and I have this method to convert the data retrieved in JSON:

while( $row = getAllMessages()->fetch_assoc()) {
        $json[] = $row;
    }
    echo json_encode( $json );

I've also tried this:

echo json_encode(getAllMessages()->fetch_assoc());

and I only get the first element/value returned from the SQL query.

Upvotes: 0

Views: 641

Answers (1)

fusion3k
fusion3k

Reputation: 11689

This code:

while( $row = getAllMessages()->fetch_assoc() ) {

produce an infinite loop: at each iteration, you call getAllMessages() and fetch first row, so while never ends unless that you have no result or boolean (False) result.

Change it in this way:

$rows = getAllMessages();
while( $row = $rows->fetch_assoc() )
{
    ...
}

Upvotes: 1

Related Questions