簡體   English   中英

使用SESSION創建購物車對象

[英]Creating shopping cart object with SESSION

如何創建我的購物車對象而不每次都覆蓋會話/對象? 我下面的代碼無法正常工作,因為每次單擊提交按鈕添加項目時,它都會從頭開始並覆蓋購物籃。

在此處查看實時版本: 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;

}

}

可能您的會話設置配置錯誤。 如果php.ini文件中的會話路徑不正確,則如果將錯誤報告設置為0,則可能實際上沒有保存該會話。

檢查您的php.ini會話部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM