0

I want to create json which contains all orders from datebase. I tried to write this code but it returns only one order.

  $query = mysql_query("SELECT * FROM orders  WHERE id_user = '".$userdata['user_login']."' ORDER BY `nom` ASC ");
    if ($query)
    {
        $i = 0;


    while ($row = mysql_fetch_assoc($query)) 
    {

    $where=$row["where"];
    $time_min=$row["time_min"];
    $time_max=$row["time_max"];
    $date1=$row["date1"];
    $date2=$row["date2"];
    $from=$row["from"];
    $id=$row["id"];
    $orders =[
    'from' => $from, 
    'where' => $where, 
    'time_min' => $time_min, 
    'time_max' => $time_max, 
    'date1' => $date1, 
    'date2' => $date2, 
    'id' => $id];
    $i++;
    }
}
$data = [ 
'count' =>$i,
'orders' => $orders
];
header('Content-type: application/json');
echo json_encode( $data );
exit;

Now the response looks like this:

now

But I want like this:

want

1
  • 1
    the mysql_* api is deprecated / obsolete and has been removed from later versions of PHP. To continue using would seem unwise - especially as your code is vulnerable potentially to sql injection. Upgrade to mysqli or PDO Commented Jan 27, 2019 at 9:40

1 Answer 1

2

Append to the $orders array:

  $query = mysql_query("SELECT * FROM orders  WHERE id_user = '".$userdata['user_login']."' ORDER BY `nom` ASC ");
    if ($query)
    {
        $i = 0;


    while ($row = mysql_fetch_assoc($query)) 
    {

    $where=$row["where"];
    $time_min=$row["time_min"];
    $time_max=$row["time_max"];
    $date1=$row["date1"];
    $date2=$row["date2"];
    $from=$row["from"];
    $id=$row["id"];
    $orders[] =[ // <--- The difference
    'from' => $from, 
    'where' => $where, 
    'time_min' => $time_min, 
    'time_max' => $time_max, 
    'date1' => $date1, 
    'date2' => $date2, 
    'id' => $id];
    $i++;
    }
}
$data = [ 
'count' =>$i,
'orders' => $orders
];
header('Content-type: application/json');
echo json_encode( $data );
exit;
Sign up to request clarification or add additional context in comments.

Comments

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.