0

I read user from the database but I return json to ajax only return the last user because I cant concatenate the json encode.

  $myObj = new \stdClass();

while ($fila = $bd->fila()) {
    $myObj->NOMBRE = $fila["NOMBRE"];
    $myObj->ROLENAME = $fila["ROLENAME"];
    $myObj->IDUSER = $fila["IDUSER"];
    $myJSON = json_encode($myObj);
}



echo $myJSON;
1
  • build a "big" array inside the loop (= add new item $myObj), then at the very end json_encode() that. Commented Jul 30, 2018 at 10:50

3 Answers 3

1

You are now overwriting $myJson in each iteration. We can also not "concatanate" two jsons (well, we could, but we shouldn't, cause it's laborious..).
Better put everything in one array/object and json_encode() at the very end.

$myObj = new \stdClass();
$users = array();  // instantiate a new array
while ($fila = $bd->fila()) {
    $myObj->NOMBRE = $fila["NOMBRE"];
    $myObj->ROLENAME = $fila["ROLENAME"];
    $myObj->IDUSER = $fila["IDUSER"];
    // add objects to that array
    $users[] = $myObj;
}
// then at the end encode the whole thing to json:
echo json_encode($users);

Now here are some variants:
If you want everything that your db is returning in this items you could shorten that to:

$users = array();  // instantiate a new array
while ($fila = $bd->fila()) {
    // add the whole item (cast as Object) to that array
    $users[] = (Object) $fila;
}
// then at the end encode the whole thing to json:
echo json_encode($users);

If you don't care if the items are objects or arrays you could skip the casting and just add the array to the big array:

 $users[] = $fila;
Sign up to request clarification or add additional context in comments.

Comments

0

Maybe if you concatenate it as array like this $myJSON[] = $myObj; and then after the while echo json_encode($myJSON);

Comments

0

You just have to collect data to big array and then encode whole array. Also there's no reason for creating new StdObjects instead of usual arrays.

// define empty array
$result = [];
while ($fila = $bd->fila()) {
    // add to the array all needed elements one by one
    $result[] = [
        'NOMBRE' => $fila["NOMBRE"],
        'ROLENAME' => $fila["ROLENAME"],
        'IDUSER' => $fila["IDUSER"],
    ];
}
// encode whole result
echo json_encode($result);

2 Comments

Your answer would be of greater quality if you explained your code. It will be useful to new users that are learning.
@Nic3500 OK, no problem. I hope it has become more useful :)

Your Answer

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.