2

I want to achieve this output in php.

[ { "id": 1388534400000, "author": "Pete Hunt", "text": "Hey there!" }, { "id": 1420070400000, "author": "Paul O’Shannessy", "text": "React is *great*!" } ] 

I have a while loop in my backend below.

$pull = "SELECT * FROM mydb"; $result = $con->query($pull); while($row = $result->fetch(PDO::FETCH_ASSOC)) { $json['id'] = $row['id']; $json['author'] = $row['author']; $json['text'] = $row['text']; } echo json_encode($json); 

It only returns the last row in the database, and I want to display them all.

Thank you.

3
  • 5
    replace $json['id'] = $row['id']; $json['author'] = $row['author']; $json['text'] = $row['text']; with $json[] = $row; Commented Mar 10, 2016 at 12:24
  • @Mark Baker Thank you for that clever answer! Works like a charm!. You should put this as answer, not as comment. Commented Mar 10, 2016 at 12:33
  • Mark Baker has the simplest answer, govindkr13 is also helpful but, Vinie makes everything clear, that's why I choose him as the best answer. Hope you guys understand. Thank you all! Cheers! Commented Mar 10, 2016 at 12:56

6 Answers 6

4

If your $row contains only these three fields from database then use below code otherwise @govindkr13 answer

$pull = "SELECT * FROM mydb"; $result = $con->query($pull); $json = []; while($row = $result->fetch(PDO::FETCH_ASSOC)) { $json[] = $row; } echo json_encode($json); 
Sign up to request clarification or add additional context in comments.

Comments

3

You are simply overwriting your $json array every time. Try this:

$i=0; while($row = $result->fetch(PDO::FETCH_ASSOC)) { $json[$i]['id'] = $row['id']; $json[$i]['author'] = $row['author']; $json[$i]['text'] = $row['text']; $i++; } echo json_encode($json); 

Comments

3

use this

$pull = "SELECT * FROM mydb"; $result = $con->query($pull); $final = []; while($row = $result->fetch(PDO::FETCH_ASSOC)) { $json['id'] = $row['id']; $json['author'] = $row['author']; $json['text'] = $row['text']; $final[] = $json; } echo json_encode($final); 

1 Comment

Thank you @govindkr13, your code works. but the simplest answer is from Mark Baker above.
2

Maybe this can help.

while($row = $result->fetch(PDO::FETCH_ASSOC)) { $json[$row['id']]['author'] = $row['author']; $json[$row['id']]['text'] = $row['text']; } 

Comments

2

$i=0; while($row = $result->fetch(PDO::FETCH_ASSOC)) { $json[$i]['id'] = $row['id']; $json[$i]['author'] = $row['author']; $json[$i]['text'] = $row['text']; $i++; } echo json_encode($json);

Comments

1

try this

$count=0; while($row = $result->fetch(PDO::FETCH_ASSOC)) { $json[$count]['id'] = $row['id']; $json[$count]['author'] = $row['author']; $json[$count]['text'] = $row['text']; $count++; } echo json_encode($json); 

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.