简体   繁体   中英

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? I am using CodeIgniter, if that helps.

Example code would also be nice.

I would recommend that you look at the CodeIgnitor Session Class .

Additionally, you could look at Chris Shiflett's discussion on this topic.

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.

Here is what I would have in the show basket function:

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.

Now last but not least, a clear basket function:

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

Don't forget session_start(); before you add any Product IDs to your session basket. Also don't forget the 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
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM