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);