I wrote this
if($stmt->execute()){
$user = $stmt->get_result();
while ($obj = $user->fetch_object()) {
echo json_encode($obj) . ",";
}
}
and it returned
{"tabId":1,"tabName":"Main","uId":"1"},{"tabId":2,"tabName":"Photography","uId":"1"},
how to remove the , to make it a valid json?
asked Apr 22, 2014 at 16:04
user3522457
3,0036 gold badges26 silver badges25 bronze badges
-
You echo a comma and you're surprised that it actually gets echoed?Mark– Mark2014年04月22日 16:08:25 +00:00Commented Apr 22, 2014 at 16:08
1 Answer 1
Each time you go around the loop, you produce a valid JSON text (followed by a comma).
When you join them together (which is the effect of echoing out each time you go around) the result is invalid.
Put the values in an array. Only call json_encode at the end.
My PHP is pretty rusty, but I think this will do the job.
$data = Array();
if($stmt->execute()){
$user = $stmt->get_result();
while ($obj = $user->fetch_object()) {
$data[] = $obj;
}
}
echo json_encode($data);
Ulrich Thomas Gabor
6,6844 gold badges31 silver badges47 bronze badges
answered Apr 22, 2014 at 16:06
Quentin
949k137 gold badges1.3k silver badges1.4k bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
user3522457
I don't get it, example?
lang-php