0

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.

6
  • I dont see anything wrong.Are you sure you have more than 1 value in the db? Commented Apr 17, 2016 at 16:40
  • @Mihai yup, there are other values within the database. They appear on the website itself, just not when I use json_encode. Commented Apr 17, 2016 at 16:41
  • In your while loop if you do echo $row[someColumn]; do you get the expected results? Commented Apr 17, 2016 at 16:42
  • @Mihai, odd, it displays the same message over and over again. Commented Apr 17, 2016 at 16:44
  • @Mihai, seems like I solved the problem. Apparently directly using while ($row = getAllMessages) doesn't work Commented Apr 17, 2016 at 16:45

1 Answer 1

1

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

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.