0

I've seen many examples on the internet (especially here) where the solution below should be able to turn the result of a database query into JSON:

    $stmt = $pdo->query('select * from TABLE;');
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($data);

but in my case this doesn't produce any JSON, although the query result contains 75 rows. A slightly different approach does return JSON:

    $stmt = $pdo->query('select * from TABLE;');
    echo "[";
    while($r = $stmt->fetch()) {
        echo json_encode($r);
    }
    echo "]";

I could go with that, but I am wondering what is going on. Why is the first approach not working?

EDIT:

this might give a clue. The code below produces [] as a result. Still not what I want, but the fetch in the while statement does 'something' .

    $stmt = $pdo->query('select * from TABLE;');
    while($r = $stmt->fetch()) {}
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($data);
Walter Brand
  • 679
  • 3
  • 9

1 Answers1

2

Why is the first approach not working?

It does. Just double check the resulting JSON.
As long as your query returns any rows, this code produces perfect, first class json.

Most likely, like other PHP users, you are checking not the immediate result but distant consequences.

If it really doesn't, then check json_last_error() and then set your database client encoding in utf8

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345