2013-03-17 80 views
0

如何在數據庫中插入多個數據?當我插入具有多個訂單的數據時,只有一個項目被插入到數據庫中。我需要幫助把它放到一個循環中。將多個數據插入到一個表中

這裏是我目前使用的代碼:

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

有什麼錯誤訊息?另外,[**請不要在新代碼中使用'mysql_ *'函數**](http://bit.ly/phpmsql)。他們不再被維護[並被正式棄用](https://wiki.php.net/rfc/mysql_deprecation)。看到[**紅框**](http://j.mp/Te9zIL)?學習[*準備的語句*](http://j.mp/T9hLWi),並使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli) - [這篇文章](http://j.mp/QEx8IB)將幫助你決定哪個。如果你選擇PDO,[這裏是一個很好的教程](http://j.mp/PoWehJ)。 – 2013-03-17 17:54:30

+0

@JohnConde。沒有錯誤消息,只是發生只有一個項目插入表中,雖然我選擇了多個項目。 – 2013-03-17 18:01:19

+0

「這是我做的,但它給了我語法錯誤,」< - 語法錯誤是什麼? – 2013-03-17 18:02:19

回答

0

你已經寫foreach($i=0,$i < $item_id_count,$i++),我認爲你的意思

for ($i=0 ; $i < $item_id_count ; $i++) 
+0

謝謝grahamj42。問題已經解決:) – 2013-03-17 18:17:38

相關問題