PHP Shopping Basket (or Cart)

The basic idea here is to create an instance of a class called Basket that represents a shopping basket or cart and it functionalities of adding to the basket/cart and removing, etc.

(NOTE: modified taken from Sample code from http://px.sklar.com/code.html/id=612 )

PHP Item class (to represent an Item ordered in the basket) AND the Basket class ....start of one...what about modify/update function?

<?php                                      
//========================================
// Class item = represents a product that is a 
//item is in shopping basket
class item {
      var $code; // code
      var $name; // name
      var $quantity; // quantity
      var $price; // price per item
      function item($code, $name, $quantity, $price) 
      {
         $this->code = $code;
         $this->name = $name;
         $this->quantity = $quantity;
         $this->price = $price;
       }
         
 }
//========================================
// Class basket = represents shopping basket with 
// the variable $session_basket representing the
// Array of item instances in basket
/**
  * shopping basket class
  */
class basket {
       /**
        * constructor
        */
      function basket() {
         $this->sessionStart();
      }
      /**
       * start session OR if one already created 
       *retrieve shopping_basket
       */
      function sessionStart() {
         global $session_basket;      //global varriable ---array of items in basket
         //start session or retrieve if already exists with client
         session_start();
         if($verbose) //verbose printout --not necessary
              echo "session id ". session_id() . "<br>";
         //if previouisly started grab data associated with session_basket
         if(isset($_SESSION['session_basket']))
              {
                  $session_basket = $_SESSION['session_basket'];
                  if($verbose) //verbose printout --not necessary 
                    {  echo "retrieved session basket is: ";
                       print_r($session_basket);
                       echo"<br>"; }
              }
         else
             {   //if no session_basket initially to empty array
                 $session_basket = Array();
                 //store in SESSION variables
                 $_SESSION['session_basket'] = $session_basket;
                if($verbose) //verbose printout --not  necessary
                    echo "session basket NEW";
                        
              }
       }
       /**
        * destory session -- call when someone want to completely CLEAR the cart --get rid of session
        */
       function sessionEnd() {
          session_unset();
          session_destroy();
       }
                       
       /**
         *determine the number of elements in basket
         */
       function basketSize() {
           global $session_basket;
           // make session if not found
           if ($session_basket == "") {
                $this->sessionStart();
           }
           if (! is_array($session_basket)) {
                         return 0;
           }
 
           return getLength($session_basket); //number of elements in the array $session_basket
      }
      /**
        * register item in session    like add or  modify something in basket/cart
        * if same code exist in session, modify it.
        *  THIS IS THE METHOD WE WILL CALL AFTER CREATING A BASKET INSTANCE TO ADD ITEMS TO BASKET OR MODIFY
        */
      function registerItem($code, $name, $quantity, $price) {
         global $session_basket;
         // make session if not found
         if ($session_basket == "") {
            $this->sessionStart();
         }
         // test to see if this product (with id $code) is currently IN basket, if so EDIT IT (update)
         if (! $this->editItem($code, $name, $quantity, $price)) {
              $item = new item($code, $name, $quantity, $price); //if NOT in basket CREATE item 
              $session_basket[] = $item;  // ADD the new item to the array $session_basket
         }
 
         //Make sure to add updated $session_basket array to the SESSION variable
         $_SESSION['session_basket'] = $session_basket;
      }
 
      /**
        * see if product (with product id $code) is in the current $session_basket array
        * if exist, modify it and return true
        * else retrun false
        */
     function editItem($code, $name, $quantity, $price) {
        global $session_basket;
        // make session if not found
        if ($session_basket == "") {
            $this->sessionStart();
            return false;
        }
        reset($session_basket);  //segt pointer in array to first element

        //cycle through elements in basket (array $session_basket) until you find the $item you want to edit
        while(list($k, $v) = each ($session_basket)) { //search in $session_basket
                
            if ($session_basket[$k]->code == $code) { //if found matching code (product id)
               // Found same code --- upade with new values the item
               $session_basket[$k]->name == $name;
               $session_basket[$k]->quantity = $quantity;
               $session_basket[$k]->price = $price;
 
               if($verbose) //verbose printout --not necessary
                   echo "INSIDE editItem: " . $code . "<br>";
 
               return true; //return true we updated it
            }
        }
 
        return false; //could not find the product in the basket
                       
     }
 
    /**
      * delete item from basket ($session_basket  array) that has product id of $code and name of $name
      */
    function deleteItem($code, $name) {
       global $session_basket;
 
       // make session if not found
       if ($session_basket == "") {
          $this->sessionStart();
       }
       reset($session_basket);  //set pointer in array to first element


       //cycle through basket (array $session_basket) and look to see if item is there
       while(list($k, $v) = each ($session_basket)) { //look through each item in basket  
           if ($session_basket[$k]->code == $code) { //if this item's code matches $code then we found the one to remove
              unset($session_basket[$k]); //remove this item from the $session_basket array
              return true;
           }
        }
    }


                  
}
                      

?>


STEP 1 This defines an object named basket

<?php

//STEP 1:  create basket
$basket = new basket(); ?>

 

 

STEP 2: Create and Add some items to the basket

YOU WILL NOT HARD CODE ITEMS LIKE THIS but, instead read in form data so you know the item you want to create to add to the basket --- for example when you invoket the code from the action statement of a form that is on a product page triggered by "Add to Basket/Cart" button

<?php
//Dummy code (you will delete) that adds 2 products statically
$basket->registerItem("asf000000", "implant", "1", "1000000");
$basket->registerItem("abcd000001", "avana implant kits", "10", "15000");
//Dummy code to register a item with product ID associated with time -- SILLY
$uniqueid = time();
$basket->registerItem($uniqueid, "avana implant kits", "10", "15000"); basket.php containing ALL the Above code PLUS the output code --STEP 3 below //THIS IS WHAT RUNNING THE ABOVE CODE LOOKS LIKE MULTIPLE TIMES --note just the
// uniquie ID item is created new each time we run the above

//Code to register an item associated with the $_POST data of pid, name, description, quantity, price $pid = $_POST['pid']; ///this is not GOOD code you should check if there is pid first value first $name = $_POST['name']; $qty = $_POST['quantity']; $price = $_POST['price']; //we are getting the price from hiddent variable in form rather than database--not great $basket->registerItem($pid, $name, $qty, $price);
?>

 

//STEP 3 Print out the basket in a table (see results above and basket.php code for details)

 


 

YOU WILL HAVE TO MODIFY THE CODE BELOW TO READ CART FROM SESSION IF IT EXIST

HERE IS A START THAT DOES IT      TRY IT OUT

MORE CODE ---that does both add/update and delete and has a form Product1.html that will
call the code cart.php to add a product/item to its basket. TRY IT OUT

Note: sometimes in other code samples dealing with sessions you see the use of the function session_register instead of
explicitly call session_start. session_register will authomatically call session_start if a session
does not already exist. See php.net for more details on this function.

 

 


PHP shopping idea ---> Calling another page

Often you want to run a script to perform some action - such as inserting an item into a shopping cart - and then return immediately to the calling, or referring, page. Indeed, we may wish to run this script from different pages and return to the calling page whatever it is. To do this, we have to (a) avoid displaying any information associated with the action script, and (b) somehow get back to the calling page whose name we cannot embed in the action script.

For example, book.php (could be a static html file) is the calling script, and enter.php is the action script. The key PHP feature that makes this work are the following three lines of enter.php:

// Return to referring page  
header("Location: $HTTP_REFERER");  
exit;  
The PHP function header() sends its arguments as a response to the HTTP request that caused the current script to be executed. The PHP variable $HTTP_REFERER stores the URL of the calling, or referring, page. If this response is the first output of the action script, the effect is to immediately return to the calling page, which is exactly what is required.

The function header() can be used to output other forms of HTTP responses. There are also many other useful PHP variables like $HTTP_REFERER, for example $PHP_SELF which is the name of the current script.

Note that the function header must be called before anything is output by the script.

 

 

ORIGINAL CODE from Sample code from http://px.sklar.com/code.html/id=612

 

 

© Lynne Grewe