doujimiao7480 2015-04-03 16:18
浏览 62

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

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?

  • 写回答

1条回答 默认 最新

  • dsdxlibt98300 2015-04-03 16:27
    关注

    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){
    
       });
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!