0

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
1
  • You echo a comma and you're surprised that it actually gets echoed? Commented Apr 22, 2014 at 16:08

1 Answer 1

3

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

1 Comment

I don't get it, example?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.