使用PHP向mysql插入一个多维数组

时间:2014-08-04 01:40:59

标签: php mysql

我试图从动态jquery表单插入这个多维数组,但我不知道如何解决这个问题。打印时,数组显示如下:

[item] => Array ( 
    [1] => Array ( 
        [unit] => service 
        [qty] => 3 
        [description] => Description 1 
        [price] => $ 33 
        [tax] => 60 % 
        [total] => $ 158.40
    ) 
    [2] => Array ( 
        [unit] => hours 
        [qty] => 74 
        [description] => Description 2 
        [tax] => 3 % 
        [total] => $ 3,429.90 ) 
    [3] => Array ( 
        [unit] => days 
        [qty] => 67 
        [description] => Description 3 
        [tax] => 6 % 
        [total] => $ 284.08 ) 
    [4] => Array ( 
        [unit] => product 
        [qty] => 72 
        [description] => Description 4 
        [tax] => 34 % 
        [total] => $ 3,183.84 
    ) 
) 

我用这个作为我的每个陈述,但它没有用:

$returnedData = $_POST['item'];

      foreach($returnedData as $data) {
                $unit = $data['unit'];
                $qty = $data['qty'];
                $description = $data['description'];
                $tax = $data['tax'];
                $price = $data['price'];
                $subtotal = $data['total'];
      }

    $insert_items = mysqli_query($connect_db,"INSERT INTO items (invoice_id, date, unit, qty, description, tax, price, subtotal) VALUES ($invoice, $todays_date, $unit, $qty, $description, $tax, $price, $subtotal)");

任何人都知道如何捕获所有数据?它是针对每个循环的吗?

1 个答案:

答案 0 :(得分:0)

这可能会对你有所帮助。因为这是一个多维数组,你可以再应用一个循环来获取值,并在第一个循环后写入INSERT查询

$returnedData = $_POST['item'];

foreach($returnedData as $value=>$data) 
{
        $unit = $data['unit'];
        $qty = $data['qty'];
        $description = $data['description'];
        $tax = $data['tax'];
        $price = $data['price'];
        $subtotal = $data['total'];

    $insert_items = mysqli_query($connect_db,"INSERT INTO items 
    (invoice_id, date, unit, qty, description, tax, price, subtotal) 
    VALUES 
    ($invoice, $todays_date, $unit, $qty, $description, $tax, $price, $subtotal)");
}