使用SESSION创建购物车对象

时间:2013-02-25 20:07:09

标签: php session shopping-cart

我应该如何创建购物车对象而不是每次都覆盖会话/对象?我下面的代码无法正常工作,因为当我每次单击提交按钮添加项目时,它都会从头开始并覆盖购物篮。

在此处查看实时版本:http://www.animportantdate.co.uk/home/products.php

我的代码是:

 session_start();
 include('oopCart.php');

 $basket = new shoppingCart($_SESSION['cart']);

 if (isset($_POST['submit'])){
      $id = $_POST['id'];
      $qty = $_POST['qty'];
      $basket->addItem($id, $qty);
 }
 ?>
   <form method="POST" action="products.php">
<input type="hidden" value="dog" name="id">
<input type="hidden" value="10" name="qty">
<input type="submit" value="buy 10 dogs" name="submit">
   </form>

  <?php
  echo '<BR>items in basket: '. $basket->countItems();
  echo '<BR>Total number of dogs (201): '. $basket->numberOfProduct('dog');
  echo '<BR>is dog in basket? '. $basket->isInCart('dog');
  ?>

编辑:我在下面添加了一些shoppingcart类。我应该提一下,当我创建对象并测试它包含在同一个php文件中的所有方法时,它工作正常。因此,这些方法都运作良好。这只是导致我出现问题的实例化。

  class ShoppingCart{

protected $id;
protected $qty;
protected $cart = array();

// constructor accepts the session variable to create cart object
function __construct($cart=""){
   $this->cart = $cart;
}

function addItem($id, $qty=1){
    if (($this->isInCart($id))  == false ){ 
        $this->cart[$id] = array( 'id' => $id, 'qty' => $qty);
    } else{
        $this->cart[$id]['qty'] += $qty;            
    }
}

function isInCart($id){
    $inCart=false;
    if ($this->cart[$id]){
        return $inCart=true;
                break;
    }   
    return $inCart;
}

public function isEmpty(){
    return (empty($this->cart));
}

function countUniqueItems(){
    if ($this->isEmpty()==false){
        foreach($this->cart as $item){
            if($item['id']){
                $uniqueItems++;
            }
        }
    }
    return $uniqueItems;

}

}

1 个答案:

答案 0 :(得分:0)

可能您的会话设置配置错误。如果php.ini文件中的会话路径不正确,则如果将错误报告设置为0,则可能实际上未保存会话。

检查你的php.ini会话部分。

相关问题