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?

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

1 Comment

I don't get it, example?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.