【问题标题】:How to add session multidimensional array into database and update in real time?如何将会话多维数组添加到数据库并实时更新?
【发布时间】:2015-06-08 18:15:19
【问题描述】:

我的数组,即 $_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

到表,因为我在$_SESSION['cart_array'] 中有两个项目。并且mysql错误显示:

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

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

【问题讨论】:

  • 这个问题非常广泛......到目前为止你有什么 php 代码?你试过什么?你在使用什么库?你的数据库连接信息是什么?

标签: php jquery session multidimensional-array


【解决方案1】:

你需要:

  • 将会话数组添加到 db 的 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){

   });
});

【讨论】:

  • 感谢您的回复@Sam Battat,但我无法执行代码,我尝试使用我的数据库表名处理您的代码,但无法成功
  • 当您通过在地址栏中输入脚本地址从浏览器运行 php 脚本时遇到什么错误?
  • 在第 42 行调用 D:\wamp\www\sandgrainstudio\php\cart-update.php 中非对象的成员函数 prepare() ......我的数据库表名称 id product_added 和 coloum 名称是 item_id,quantity,unit_price....就像在数组中一样
  • 好吧,我的代码假设您已经建立了数据库连接并且您正在使用 PDO,这是您必须首先建立的连接$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-25
  • 2013-02-28
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 2021-10-04
  • 1970-01-01
相关资源
最近更新 更多