将多个数据插入到一个表中
问题描述:
如何在数据库中插入多个数据?当我插入具有多个订单的数据时,只有一个项目被插入到数据库中。我需要帮助把它放到一个循环中。将多个数据插入到一个表中
这里是我目前使用的代码:
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());
}
}
}
我怎样才能正确地写入循环?
答
你已经写foreach($i=0,$i < $item_id_count,$i++)
,我认为你的意思
for ($i=0 ; $i < $item_id_count ; $i++)
+0
谢谢grahamj42。问题已经解决:) – 2013-03-17 18:17:38
有什么错误讯息?另外,[**请不要在新代码中使用'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
@JohnConde。没有错误消息,只是发生只有一个项目插入表中,虽然我选择了多个项目。 – 2013-03-17 18:01:19
“这是我做的,但它给了我语法错误,” 2013-03-17 18:02:19