0

Hey i am trying to add my selected resultset into an array to send it as a response to my angularjs function

this is my code

include 'dbconnect.php';

global $mysqli;

$sql = "SELECT `id`, `name`, `stock`, `pzn` FROM `pda_articles`"; 

$result = mysqli_query($mysqli, $sql) OR die(mysqli_error($mysqli));

$data = array();

if($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    print json_encode($data);
} else {
    echo "no";
}

$data[] = $row should work but it doesnt.. $data[] = $row['id'] works but i have no idea how to add the other columns...

maybe you could help me

this is my output with console.log

enter image description here

Thanks :)

Torben G
  • 750
  • 2
  • 11
  • 33

3 Answers3

0

you should build the array and populate it with keys and data then use array push

$data = array();
while($row = mysqli_fetch_assoc($result)) {
        $col['id'] = $row['id'];
        $col['name'] = $row['name'];    
        $col['stock'] = $row['stock'];    
        array_push($data,$col);

}
    echo json_encode($data);
Gert
  • 360
  • 3
  • 8
0

if i write $data = var_dump($row); and open it into the browser it gives me that output:

array(4) { ["id"]=> string(1) "1" ["name"]=> string(22) "Handschuhe Vinyl Gr. M" ["stock"]=> string(1) "7" ["pzn"]=> string(6) "990304" } array(4) { ["id"]=> string(1) "2" ["name"]=> string(22) "Handschuhe Latex Gr. M" ["stock"]=> string(1) "7" ["pzn"]=> string(6) "990238" } array(4) { ["id"]=> string(1) "3" ["name"]=> string(22) "Handschuhe Latex Gr. L" ["stock"]=> string(1) "2" ["pzn"]=> string(6) "990267" } array(4) { ["id"]=> string(1) "4" ["name"]=> string(26) "Fl�chendesinfektionsmittel" ["stock"]=> string(1) "8" ["pzn"]=> string(8) "10795578" } null

Torben G
  • 750
  • 2
  • 11
  • 33
0

You have to use whole the code in object oriented way like this:

$result = $mysqli->query($sql);
$data = array();
if($result->num_rows > 0) {
   while ($row = $result->fetch_assoc()) {
      $data[] = $row;
   }
}
echo json_encode($data);

If it doesn't work, then there will be some other issue. try printing $row in the loop start.

Maha Dev
  • 3,915
  • 2
  • 31
  • 50