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

My array i.e $_SESSION['cart_array'] contains:

Array ( [0] => Array ( [item_id] => abc123 [quantity] => 2 [unit_price] => 500 ) [1] => Array ( [item_id] => def456 [quantity] => 3 [unit_price] => 100 ) )

I am using this code to insert into my database:

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"; }

My problem is when I run the script it add only one item ie:

item_id=qwerty,quantity=2 and unit_price=500

to the table where as I have two items in the $_SESSION['cart_array']. And mysql error shows:

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

How to entry two and multiple items into database?

You will need:

  • a php script that adds the session array to db
  • a jquery code to call the php script via an ajax request to trigger the insertion

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){

   });
});