WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDES  |  PHP CLASSES  |  CODE SEARCH  |  ARTICLES SEARCH  |  PHP FORUMS  |  PHP MANUAL  |  PHP FUNCTIONS LIST  |  WEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
WeberDev's Monthly code contest PHP Code Contest
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Index
PHP Web Logs (BLogs)
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
Submit Site
Forex Trading Online forex trading platform

Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : shopping cart class with add/edit/delete product functionality.
Categories : PHP, PHP Classes, Ecommerce Click here to Update Your Picture
Ben Barnett
Date : May 21st 2004
Grade : 5 of 5 (graded 1 times)
Viewed : 8428
File : 3865.php
Images : No Images for this code example.
Search : More code by Ben Barnett
Action : Grade This Code Example
Tools : My Examples List

  Submit your own code examples 
 



Shopping Cart Class

@author Ben Barnett <ludge@spymac.com>
        
        
Shopping Cart Class

This module is a shopping cart class with add/edit/delete product functionality.
Each item is stored in a session variable as an array with the productID being the key
and the quantitly of the item as the value. The cookie stores the serialized cart contents
between visits.
IMPORTANT NOTE: The show_cart function
outputs a very bland table so you will need to edit this to beautify it.

<?php
class cart
{
   
   
/**
    * The expiry time for the cart cookie
    */
   
var $expire = 3600;
   
   
    var
$del_cookie = -1;
   
   
/**
    * Class constructor
    *
    * Start the session, if the cart doesn't exist as a session variable, check for a cookie,
    * if the cookie isn't there, make a new cart.
    */
   
function cart()
    {
   
// Start the session.
   
session_start();
   
   
$time = time();
   
$this->expire = $time + $this->expire;
   
   
// If the session variables haven't been registered yet, do that now.
   
if(!isset($_SESSION['cart']))
        {
       
        if(isset(
$_COOKIE['cart']))
            {
           
$_SESSION['cart'] = array();
           
$_SESSION['cart'] = unserialize(stripslashes($_COOKIE['cart']));
           
$_SESSION['total_items'] = $this->cart_calculate_items($_SESSION['cart']);
           
$_SESSION['total_price'] = $this->cart_calculate_price($_SESSION['cart']);
            }
        else
            {
           
$_SESSION['cart'] = array();
           
$_SESSION['total_items'] = 0;
           
$_SESSION['total_price'] = 0.00;
           
           
$s_cart = serialize($_SESSION['cart']);
           
setcookie('cart', $s_cart, $this->expire);
            }
        }
   

    }
   
   
   
   
/**
    * Displays the cart
    *
    * @param array $cart The cart you want to display.
    * @param boolean $pictures Show pictures in cart? (default=false)
    * @param boolean $editable Is cart editable? (default=true)
    */
   
function cart_show($cart, $pictures = 'false', $editable = 'true')
    {
    require(
$_SERVER['DOCUMENT_ROOT'].'/path/to/database/connection_code.php');
   
mysql_select_db($database_connAT, $connAT);
    echo
"<table border=\"1\"><tr><td>Product</td><td>Quantity</td><td>Price</td></tr>\n";
    foreach(
$cart as $productID => $qty)
        {
       
$product = $this->cart_get_item_details($productID);
        echo
"<tr>\n";
        echo
"<td>".$product['details']."</td><td>".$qty."</td><td>£".$product['price']."</td>\n";
        echo
"</tr>\n";
        }
    echo
'</table>';
    }

   
   
   
/**
    * Adds an item to the cart.
    *
    * If the item is already in the cart, it increments the quantity by one.
    * Otherwise, it adds one of the selected item to the cart. It then recalculates
    * the number of items in the cart and the total cost.
    *
    * @param string $item The productID to be added.
    */
   
function cart_add_item($item)
    {
   
// If cart item exists, increment it by one...
   
if(isset($_SESSION['cart'][$item]))
        {
       
$_SESSION['cart'][$item]++;
       
        }
       
   
// ...otherwise add it as a new item.
   
else
        {
       
$_SESSION['cart'][$item] = 1;
        }
   
   
// Recalculate totals
   
$_SESSION['total_items'] = $this->cart_calculate_items($_SESSION['cart']);
   
$_SESSION['total_price'] = $this->cart_calculate_price($_SESSION['cart']);
   
$s_cart = serialize($_SESSION['cart']);
   
setcookie('cart', $s_cart, $this->expire);
    }

   
   
   
/**
    * Removes a product from the cart.
    *
    * Removes a product totally from the cart by unsetting it's key and value
    * from the session array.
    */
   
function cart_delete_item($productID)
    {
   
// Unset product variable
   
unset($_SESSION['cart'][$productID]);
   
   
// Recalculate totals
   
$_SESSION['total_items'] = $this->cart_calculate_items($_SESSION['cart']);
   
$_SESSION['total_price'] = $this->cart_calculate_price($_SESSION['cart']);
   
$s_cart = serialize($_SESSION['cart']);
   
setcookie('cart', $s_cart, $this->expire);
    }

   
   
/**
    * Edits the number of each item in the cart
    *
    * If the number is set to zero, remove the item by unsetting the session variable. If
    * the number is anything else, set it the that number.
    *
    * @todo I'm not sure if this function needs any parameters passed to it to work
    * so if it doesn't, this could be why.
    */
   
function cart_edit_item()
    {
   
// Make sure the variables are being POSTed
   
if(isset($_POST['update']))
        {
        foreach(
$_SESSION['cart'] as $productID => $qty)
            {
            if(
$_POST['$productID'] ==  0)
                {
                unset(
$_SESSION['cart'][$productID]);
                }
            else
                {
               
$_SESSION['cart'][$productID] = $_POST['productID'];
                }
            }
        }
   
// Recalculate totals
   
$_SESSION['total_items'] = $this->cart_calculate_items($_SESSION['cart']);
   
$_SESSION['total_price'] = $this->cart_calculate_price($_SESSION['cart']);
   
$s_cart = serialize($_SESSION['cart']);
   
setcookie('cart', $s_cart, $this->expire);
    }
   
   
   
   
/**
    * Calculates the number of items in the cart.
    *
    * Calculates the number of items in the cart by looping through the cart incrementing
    * the number of items for each product.
    *
    * @param array $cart The cart to count items in.
    * @return integer The number of items in the cart.
    */
   
function cart_calculate_items($cart)
    {
   
// Initialise variable to default value
   
$items = 0;
   
   
// Make sure the cart is actully an array!
   
if(is_array($cart))
        {
       
// Loop through the cart and add the quanity of each item the the total
       
foreach($_SESSION['cart'] as $productID => $qty)
            {
           
$items += $qty;
            }
        }
   
// Return the total number of items
   
return $items;
    }
   
   
   
   
/**
    * Calculates the total price of the cart contents.
    *
    * This function is one of the slowest in this application
    * as it has a long database query to carry out and total up.
    *
    * @param array $cart The cart to total the price in.
    * @return float The total price of cart contents.
    */
   
function cart_calculate_price($cart)
    {
   
// Initialise variable to default value
   
$price = 0.00;
   
   
// Make sure the cart is actully an array!
   
if(is_array($cart))
        {
       
       
/**
        * Require the database connection for finding prices.
        */
       
require($_SERVER['DOCUMENT_ROOT'].'/path/to/database/connection_code.php');
       
mysql_select_db($database_connAT, $connAT);
       
       
// Loop through the cart array matching prices to products
       
foreach($cart as $productID => $qty)
            {
           
$query = "SELECT price FROM stock WHERE productID='$productID'";
           
$result = mysql_query($query);
           
           
// Then adding the (item price * quantity) to the total price
            //  and starting the loop again
           
if($result)
                {
               
$row_result = mysql_fetch_assoc($result);
               
$item_price = $row_result['price'];
               
$price += $item_price*$qty;
                }
            }
        }
   
// Return the total price
   
return $price;
    }
   
   
    function
cart_get_item_details($productID)
        {
       
$query = "SELECT * FROM stock WHERE productID='$productID'";
       
$result = mysql_query($query);
       
$row_result = mysql_fetch_assoc($result);
        return
$row_result;
        }
   
}

// Ussage Example
$cart = new cart();

// Add product number 250
cart_add_item(250);

// show the contents
cart_show($_SESSION['cart']);

// Remove product number 250
cart_delete_item(250);
?>



Authorize.net AIM Interface Class v1.0.0
Categories : PHP, PHP Classes, Ecommerce, Payment Gateways
an example of the cyberlib payment class
Categories : PHP, PHP Classes, Ecommerce, Credit Cards
ECHO-PHP Class Real Time Transaction Processor v1.4.4 for Credit Cards and Checks / ACH
Categories : PHP Classes, Cybercash, Classes and Objects, Ecommerce, PHP
simple shopping cart for php3
Categories : PHP, PHP Classes, Complete Programs, Ecommerce
Example Shopping cart class
Categories : Ecommerce, PHP, PHP Classes
a class for doing payments to a cybercash server
Categories : Ecommerce, Complete Programs, PHP Classes, PHP
Credit Card Identification and Validation Class - The credit_card class provides methods for cleaning, validating and identifying the type of credit card numbers.
Categories : PHP, PHP Classes, Credit Cards, Ecommerce, Algorithms
file class , uploade file , download file already uploaded on another website
Categories : PHP, PHP Classes, Filesystem, Web Services
phpAds, a complete banner and ad management system with detailled tracking and stats.
Categories : MySQL, Complete Programs, Ecommerce, PHP, Databases
crop and resize image class using gd library function
Categories : PHP, PHP Classes, GD image library, Graphics
open source online php shop project ecommerce commerce
Categories : PHP, Ecommerce
News management class
Categories : PHP, PHP Classes, Beginner Guides
The class to check load time of your script VERY usefull for relatively slow applications, but not only..
Categories : PHP, PHP Classes, Debugging
Expose - PHP template engine, supports server and client-sided caching,a plugin system, multiple languages, template script language is based on PHP itself.
Categories : PHP, PHP Classes, Templates, Complete Programs
RSS parser. Parses RSS into an array. Quick and nasty but does the job. No checking is done for correct Tags, only correct XML. PHP4 needed to display result (uses print_r).
Categories : PHP, XML, PHP Classes, Rich Site Summary (RSS)