sukkis
sukkis

Reputation: 322

How to encode multiple MySQLi result into correct json format?

if ($result->num_rows > 0) {

     // output data of each row
     while($row = $result->fetch_assoc()) {

$post_data = array(
    'item' => array(
    'ID' => $row["id"],
    'Name' => $row["name"],
    'Category' => $row["category"],
    'Saldo' => $row["saldo"],
    'Editor' => $row["editor"],
    'Edited' => $row["reg_date"]
  )
);
echo json_encode($post_data);

That outputs:

{"item":{"ID":"123456","Name":"Chair","Category":"Trashes","Saldo":"40","Editor":"Seppo","Edited":"2015-09-15 13:54:36"}}{"item":{"ID":"123888","Nimi":"Cheese","Kategoria":"Food","Saldo":"3","Editor":"Jorma","Edited:"2015-09-15 14:14:17"}}

When it should look something like that:

[{"item":{"ID":"123456","Name":"Chair","Category":"Trashes","Saldo":"40","Editor":"Seppo","Edited":"2015-09-15 13:54:36"}},{"item":{"ID":"123888","Nimi":"Cheese","Kategoria":"Food","Saldo":"3","Editor":"Jorma","Edited:"2015-09-15 14:14:17"}}]

Which is not in correct json format. How should I edit that code so all my mysql items passes.

I have out of my mind even long time goggling results..

Upvotes: 2

Views: 364

Answers (1)

Chris Magnussen
Chris Magnussen

Reputation: 1527

You are resetting the $post_data in every iteration. You should just append to it.

if ($result->num_rows > 0) 
{
    while($row = $result->fetch_assoc()) 
    {
        $post_data[] = array(
            'item' => array(
                'ID' => $row["id"],
                'Name' => $row["name"],
                'Category' => $row["category"],
                'Saldo' => $row["saldo"],
                'Editor' => $row["editor"],
                'Edited' => $row["reg_date"]
            )
        );
    }

    echo json_encode($post_data);
}

Upvotes: 1

Related Questions