我的数组,即$_SESSION['cart_array']包含:
Array ( [0] => Array ( [item_id] => abc123 [quantity] => 2 [unit_price] => 500 ) [1] => Array ( [item_id] => def456 [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 and unit_price=500
到表中,因为我在CCD_ 1中有两个项目。mysql错误显示:
错误:您的SQL语法有错误;查看与MySQL服务器版本相对应的手册,了解在第1行"1"附近使用的正确语法
如何在数据库中输入两个或多个项目?
您将需要:
- 将会话数组添加到数据库的php脚本
- 通过ajax请求调用php脚本以触发插入的jquery代码
PHP:
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
stmt = $dbh->prepare("INSERT INTO sessions_tbl (name, value) VALUES (:name, :value)");
foreach($_SESSION['cart_array'][0] as $key => $val){
$stmt->bindParam(':name', $key);
$stmt->bindParam(':value', $val);
$stmt->execute();
}
?>
JS:
$('ADD-TO-CART-BTN').on('click', function(){
$.post('http://yourwebsite.com/session-update-script.php', {}, function(response){
});
});