0

I have a json array list as below.I am trying to insert each item as separate row in mysql table

 {"order_array":

  [{
   "qty":"1",
   "menu_name":"PARATHA (KAZI FARMS) 20 PCS",
   "sub_total":"265.0"
   },
 
   {
    "qty":"2",
    "menu_name":"PARATHA (KAZI FARMS) 10 PCS",
    "sub_total":"300.0"
   }],
  
  "amount":
         {
          "sub_total":"565.0",
          "discount":"0",
          "wallet":"0",
          "total_price":595,
          "delivery_charges":30           
         }
 }

I have written below code but it is not inserting any data

$data = json_decode($_POST['json_order_list'], true);

foreach ($data as $row) {
   
   foreach ($array["order_array"] as $row) 
   {
      $item_name = $row['menu_name'];
      $qty = $row["qty"];
      $amount = $row['sub_total'];
      $order_id = '1';
      
      $sql_order = "INSERT INTO tbl_orders (item_name, qty, amount, order_id) 
            VALUES ('$item_name','$qty','$amount','$order_id')";
            
      mysqli_query($link, $sql_order);

    }
 }

what's wrong I am doing

Mithu
  • 665
  • 1
  • 8
  • 38

1 Answers1

3

For your data structure nested loop is redundant. You can use next code as solution:

$stmt = mysqli_prepare(
    $link, 
    "INSERT INTO tbl_orders (item_name, qty, amount, order_id) VALUES (?,?,?,?)"
);
   
foreach ($data["order_array"] as $row) 
{
    $item_name = $row['menu_name'];
    $qty = $row["qty"];
    $amount = $row['sub_total'];
    $order_id = '1';
    
    mysqli_stmt_bind_param($stmt, 'sddd', $item_name, $qty, $amount, $order_id);
    
    mysqli_stmt_execute($stmt);

}

Look working code at PHPize.online

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39