Location: PHPKode > scripts > Flexible cart > basketclass.php
<?php # ========================================================================#
   #
   #  Author:    Mano Kalousdian
   #  Version:	 1.0
   #  Date:      july 30, 2010
   #  Purpose:   class handling the shipping cart
   #  Requires : Requires PHP4 or PHP5
   #  Usage Example:
   #            $bas=new basket();
   #			$bas->init('m_cart');              initialize the basket
   #			$bas->add_cart("100:::",3);        adding values
   #			$bas->add_cart("1:::black",5);     adding values
   #			$bas->add_cart("3:::white",1);     adding values
   #			$bas->update_cart("3:::white",5);  update cart
   #			$bas->remove_cart("3:::white");    remove cart
   #			$bas->removeall_cart();            remove all cat
   #			if(!$bas->get_cart()){             checking if the cart is empty or not
   #				echo "no basket found";
   #			}else{
   #				print_r($bas->get_cart());      this returns the values stored in a array , you can iterate and get the values after that
   #			}
   #
   #			echo "<BR>";
   #			echo $bas->count_cart()." items found";   for ex if the buyer bought 3 black pencils, 2 shirts, and 5 books , the value would be 3
   #
   #			echo "<BR>";
   #			echo $bas->countall_cart()." total items found"; for ex if the buyer bought 3 black pencils, 2 shirts, and 5 books , the value would be 10
   # ========================================================================#
class basket{
private $cart=array();
public $sessionname;

function basket(){
    if(session_id()==""){
		session_start();
	}
}

function init($sessionname){
	 $this->sessionname=$sessionname;
    //initializing cart and getting value from session if it exists
	$this->cart=(isset($_SESSION[$this->sessionname]))?$_SESSION[$this->sessionname]:array();
	$this->writesession($this->cart);
}

function add_cart($id,$quantity){

	if(!isset($this->cart[$id])){
		$this->cart["$id"]=$quantity;
	}else{
		 $this->cart["$id"]=$this->cart["$id"]+$quantity;
	}
	$this->writesession($this->cart);
	return true;
}

function writesession($cart){
	$_SESSION[$this->sessionname]=$cart;
	return true;
}

function get_cart(){
	if(count($_SESSION[$this->sessionname])==0){
	   return false;
	}else{
	   return $_SESSION[$this->sessionname];
	}
	

}

function update_cart($id,$quantity){
	$this->cart["$id"]=$quantity;
	$this->writesession($this->cart);
}

function remove_cart($id){
	unset($this->cart["$id"]);
	//if there are no items left in the cart, initialize cart again
	if(count($this->cart)==0){
		$this->cart=array();
	}
	$this->writesession($this->cart);
}

function removeall_cart(){
	unset($this->cart);
	$this->cart=array();
	$this->writesession($this->cart);
}

function count_cart(){
	return count($this->cart);
}

function countall_cart(){
	$count=0;
	foreach($this->cart as $a=>$b){
		$count+=$b;
	}
	return $count;
}

}

?>
Return current item: Flexible cart