我的数组,即 $_SESSION['cart_array'] 包含
Array ( [0] => Array ( [item_id] => qwerty [quantity] => 2 [unit_price] => 500 ) [1] => Array ( [item_id] => skjbm [quantity] => 3 [unit_price] => 100 ) )
插入我的数据库代码的代码是
foreach($_SESSION['cart_array'] as $each_item){ $sql=mysql_query("INSERT INTO product_added(id,ip_address,order_id,email,item_id,unit_price,quantity,total,pay_status)values('','','','','".$each_item['item_id']."','".$each_item['quantity']."','".$each_item['unit_price']."','','')");
if(!mysql_query( $sql)){
// maybe not the best use of `die` here?
die('Error: ' . mysql_error());
}echo "record added"; }
我的问题是,当我运行脚本时,它只添加一项,即: item_id=qwerty,quantity=2 和 unit_price=500 到表中,因为我在 $_SESSION['cart_array'] 中有两项
.
mysql错误显示:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1
如何将两个或多个项目输入数据库?
最佳答案
尝试这样。顺便说一句 mysql
已弃用,使用 mysqli
$insert_query = 'INSERT INTO product_added (id,ip_address,order_id,email,item_id,unit_price,quantity,total,pay_status) values ';
foreach($_SESSION['cart_array'] as $each_item){
$insert_query .= "('','','','','".$each_item['item_id']."','".$each_item['quantity']."','".$each_item['unit_price']."','',''),";
}
$query = rtrim($insert_query, ',');
if(!mysql_query($query)){
die('Error: ' . mysql_error());
}else{
echo "record added";
}
关于php - 如何将多维数组插入数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29437714/