Array does not go full through json

Asked

Viewed 37 times

0

Good night,
I am trying to pass an array to json but it only passes the last variable

function GetSuppliersView() {
    global $db;
    global $id;
    global $type;
    try{
        $query = $db->query("SELECT * FROM suppliers WHERE id = $id");
        $row=$query->fetch(PDO::FETCH_ASSOC); 
        $result['success'] = true;
        $result['result'] = $row;
        $querytwo = $db->query("SELECT name FROM third_party_services LEFT JOIN suppliers_services ON third_party_services.id = suppliers_services.id WHERE supplier_id=$id");
        $x=0;
        while($services = $querytwo->fetch(PDO::FETCH_ASSOC)) {
             $var[$x] = $services['name'];
        }
        $result['secondresult'] = array_values($var);
        echo json_encode($result);
    return true;
    } catch (PDOException $pe) {
        return false;
    }
}

The variable $result['result'] passes right, but the $result['secondresult'] only passes the last item to be assigned

  • Forehead to wear $row=$query->fetch_assoc(PDO::FETCH_ASSOC); so you have an array that you can export with json_encode and echo.

  • The $x is always 0, does not increase, it is expected that only the last.

1 answer

1

According to your code:

$x = 0; // <<<

while($services = $querytwo->fetch(PDO::FETCH_ASSOC)) {
     $var[$x] = $services['name'];
}

The $x will always be 0, you have several options to fix this:

$x = 0;

while($services = $querytwo->fetch(PDO::FETCH_ASSOC)) {
      $var[$x] = $services['name'];
      $x++; // <<<
}

This will always increment the previous value (if it is int will be 0, 1, 2, 3...). If you want to use $x = $x + 1 as an alternative, the $x++ may have some "unexpected" effects in some cases, not in this.

However if he leaves from 0, can simply use:

while($services = $querytwo->fetch(PDO::FETCH_ASSOC)) {
      $var[] = $services['name'];
}

Mysqli owns the mysqli_fetch_all(). The PDO seems to have the equivalent fetchAll(), according to the documentation. It seems to get all the results, so try also see the fetchAll().

This is supposed to work too:

$querytwo = $db->query("SELECT name FROM third_party_services LEFT JOIN suppliers_services ON third_party_services.id = suppliers_services.id WHERE supplier_id=$id");

$result['secondresult'] = $querytwo->fetchAll();

echo json_encode($result);

But I’m not entirely sure. ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.