Array does not pass completely through json

0

Good night,
I'm 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'] goes well, but $ result ['secondresult'] only passes the last item to be assigned

    
asked by anonymous 16.06.2017 / 06:50

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 it will be 0, 1, 2, 3 ...). If you want to use $x = $x + 1 as an alternative, $x++ may have some "unexpected" effects in some cases, not this one.

However, if it starts from 0 , you can simply use:

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

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

Supposedly this should work as well:

$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. ;)

    
16.06.2017 / 08:11