【发布时间】:2013-03-17 17:53:39
【问题描述】:
如何在数据库中插入多条数据?当我插入具有多个订单的数据时,数据库中只插入了一项。我需要帮助把它变成一个循环。
这是我目前使用的代码:
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());
}
}
}
如何正确编写循环?
【问题讨论】:
-
错误信息是什么?另外,Please, don't use
mysql_*functions in new code。它们不再维护and are officially deprecated。看到red box?改为了解prepared statements,并使用PDO 或MySQLi - this article 将帮助您决定哪个。如果你选择 PDO,here is a good tutorial. -
@JohnConde 。没有错误消息,只是碰巧在表格中插入了一项,尽管我选择了多项。
-
“这是我所做的,但它给了我语法错误,”
-
foreach($i=0,$i