Php 如何将会话多维数组添加到数据库中并实时更新?

Php 如何将会话多维数组添加到数据库中并实时更新?,php,jquery,session,multidimensional-array,Php,Jquery,Session,Multidimensional Array,我的数组即$\u会话['cart\u array']包含: Array ( [0] => Array ( [item_id] => abc123 [quantity] => 2 [unit_price] => 500 ) [1] => Array ( [item_id] => def456 [quantity] => 3 [unit_price] => 100 ) ) 我正在使用此代码向我的数据库中插入: foreach($_SESSION['c

我的数组即$\u会话['cart\u 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
我在
$\u会话['cart\u array']
中有两个项目。mysql错误显示:

错误:您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以了解第1行“1”附近使用的正确语法

如何将两个或多个项目输入数据库?

您需要:

  • 将会话数组添加到数据库的php脚本
  • jquery代码,通过ajax请求调用php脚本以触发插入
PHP:


感谢您的回复@Sam Battat,但我无法执行代码,我尝试使用我的db表名处理您的代码,但无法成功当您通过在地址栏中键入脚本地址从浏览器运行php脚本时,会出现什么错误?调用成员函数prepare()在D:\wamp\www\sandgrainstudio\php\cart-update.php中的非对象上,第42行……添加了我的数据库表名id product_,冒号为item_id、quantity、unit_price……正如在arraywell中一样,我的代码假设您已经建立了db连接,并且正在使用PDO这里是您必须首先建立的连接
$dbh=new PDO('mysql:host=localhost;dbname=test',$user,$pass);
这个问题非常广泛……到目前为止你有什么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();
}
?>
$('ADD-TO-CART-BTN').on('click', function(){
   $.post('http://yourwebsite.com/session-update-script.php', {}, function(response){

   });
});