将多个数据插入一个表中

时间:2013-03-17 17:53:39

标签: php mysql loops for-loop

如何在数据库中插入多个数据?当我插入具有多个订单的数据时,只在数据库中插入一个项目。我需要帮助把它放到一个循环中。

这是我目前正在使用的代码:

foreach ($_SESSION["cart_array"] as $each_items){
    $item_id = $each_items['item_id'];
    $quantity = $each_items['quantity'] ;
    $sql = mysql_query("SELECT * FROM product WHERE id = '$item_id'");
    while($row = mysql_fetch_array($sql)){
    $product_name = $row['name'];
    $price = $row['price'];
    $total_price = $price * $quantity;
    mysql_query("INSERT INTO customer_order(
    id,quantity,item_id,
    total_price,shipping_address,
    shipping_date,customer_id)
    VALUES ('','$quantity','$item_id','$total_price',
    '','',
    '$lastId')") or die (mysql_error());
    }
}

这是我尝试的但是它产生了语法错误:

foreach ($_SESSION["cart_array"] as $each_items){
    $item_id = $each_items['item_id'];
    $item_id_count = count($item_id) ;
    $quantity = $each_items['quantity'] ;
    $sql = mysql_query("SELECT * FROM product WHERE id = '$item_id'");
    while($row = mysql_fetch_array($sql)){
       $product_name = $row['name'];
       $price = $row['price'];
       $total_price = $price * $quantity;
       foreach($i=0,$i < $item_id_count,$i++){
          mysql_query("INSERT INTO customer_order(
          id,quantity,item_id,
          total_price,shipping_address,
          shipping_date,customer_id)
          VALUES ('','$quantity','$item_id','$total_price',
          '','',
          '$lastId')") or die (mysql_error());
       }
    }
}

如何正确编写循环?

1 个答案:

答案 0 :(得分:0)

你写过foreach($i=0,$i < $item_id_count,$i++)我觉得你的意思

for ($i=0 ; $i < $item_id_count ; $i++ )
相关问题