简体   繁体   English

如何使用数据库和PHP会话来存储用户的购物车?

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

How can I use a database and PHP sessions to store a user's shopping cart? 如何使用数据库和PHP会话来存储用户的购物车? I am using CodeIgniter, if that helps. 我正在使用CodeIgniter,如果这有帮助的话。

Example code would also be nice. 示例代码也不错。

I would recommend that you look at the CodeIgnitor Session Class . 我建议您查看CodeIgnitor会话类

Additionally, you could look at Chris Shiflett's discussion on this topic. 此外,您可以查看Chris Shiflett关于此主题的讨论

I would write an add to basket function like this: 我会像这样写一个添加到篮子的函数:

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

In this shopping basket function we save Product IDs in an session array. 在此购物篮功能中,我们将产品ID保存在会话数组中。

Here is what I would have in the show basket function: 这是我在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];
        }
}

For each ProudctID in our session basket we make a SQL query to output product information. 对于我们会话篮中的每个ProudctID,我们进行SQL查询以输出产品信息。

Now last but not least, a clear basket function: 现在最后但并非最不重要,一个明确的篮子功能:

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

Don't forget session_start(); 不要忘记session_start(); before you add any Product IDs to your session basket. 在将任何产品ID添加到会话篮之前。 Also don't forget the mysql_connect(); 另外不要忘记mysql_connect(); function, you need this before you make any queries with the database. 函数,在对数据库进行任何查询之前需要这个。

how about this ; 这个怎么样 ; - when guest add one item product in the cart - 当客人在购物车中添加一件商品时

  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