簡體   English   中英

如何使用數據庫和PHP會話來存儲用戶的購物車?

[英]How can I use a database and PHP sessions to store a user's shopping cart?

如何使用數據庫和PHP會話來存儲用戶的購物車? 我正在使用CodeIgniter,如果這有幫助的話。

示例代碼也不錯。

我建議您查看CodeIgnitor會話類

此外,您可以查看Chris Shiflett關於此主題的討論

我會像這樣寫一個添加到籃子的函數:

function AddToBasket(){
    if(is_numeric($_GET["ID"])){
        $ProductID=(int)$_GET["ID"];
        $_SESSION["Basket"][]=$ProductID;
        $sOut.=ShowBasketDetail();
        return $sOut; 
    }
}

在此購物籃功能中,我們將產品ID保存在會話數組中。

這是我在show basket函數中的內容:

function ShowBasket(){
    foreach($_SESSION[Basket] as $ProductID){
        $sql="select * from products where ProductID=$ProductID";
        $result=mysql_query($sql);
        $row=mysql_fetch_row($result);
        echo "Product: ".$row[0];
        }
}

對於我們會話籃中的每個ProudctID,我們進行SQL查詢以輸出產品信息。

現在最后但並非最不重要,一個明確的籃子功能:

function ClearBasket(){
    unset($_SESSION[Basket]);
}

不要忘記session_start(); 在將任何產品ID添加到會話籃之前。 另外不要忘記mysql_connect(); 函數,在對數據庫進行任何查詢之前需要這個。

這個怎么樣 ; - 當客人在購物車中添加一件商品時

  function addCartItem($item_id, $qty)
  {
    $basket = $this->session->userdata('basket');
    if(!$basket)
    {
       $this->session->set_userdata('basket', array($item_id => $qty));
    }
    else
    {
       ## get array from $basket and *merge some new value from input
    }
  }

暫無
暫無

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

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