Friday, December 24, 2010

Example Shopping cart class



<?
/*
A simple shopping cart class that I wacked up ages ago when i was bored.
No payment function has been written mainly because it depends on the implementation.
I leave the payment function up to the programmer :)
*/

class cart
{
function get_sess()
                {
                 return str_replace("PHPSESSID=", "", SID);
                }
                
function check_item($pid){
                
$query = "SELECT * FROM cart WHERE session='".$this->get_sess()."' AND pid='$pid' ";
$result = mysql_query($query);

if(!$result)
{
return 0;
}

$numRows = mysql_num_rows($result);

if($numRows == 0)
{
return 0;
} else {
$row = mysql_fetch_array($result);
return $row['quantity'];
}
}

function add($pid, $quantity)
{
                
$qty = $this->check_item($pid);
if($qty == 0)
{
$query = "INSERT INTO cart (session, pid, quantity) VALUES ";
$query .= "('".$this->get_sess()."', '$pid', '$quantity') ";
mysql_query($query);
} else {
$quantity += $qty;
$query = "UPDATE cart SET quantity='$quantity' WHERE session='".$this->get_sess()."' AND ";
$query .= "pid='$pid' ";
mysql_query($query);
}
}

function remove($pid)
{
                
$query = "DELETE FROM cart WHERE session='".$this->get_sess()."' AND pid='$pid' ";
mysql_query($query);
}

function modify_quantity($pid, $quantity)
{
                
$query = "UPDATE cart SET quantity='$quantity' WHERE session='".$this->get_sess()."' ";
$query .= "AND pid='$pid' ";
mysql_query($query);
}

function clear()
{
                
$query = "DELETE FROM cart WHERE session='".$this->get_sess()."' ";
mysql_query($query);
}

function total()
{
                
$result = mysql_query('SELECT sum(product.price * cart.quantity) as price FROM product, cart WHERE cart.session=\''.$this->get_sess().'\' AND product.pid = cart.pid');
$row = mysql_fetch_array($result);
return $row['price'];
}

function contents()
{
                
$count = 0;
$query = "SELECT * FROM cart WHERE session='".$this->get_sess()."'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$query = "SELECT * FROM product WHERE pid='".$row['pid']."' ";
$result_inv = mysql_query($query);
$row_inventory = mysql_fetch_array($result_inv);
$contents[$count]["pid"] = $row_inventory['pid'];
$contents[$count]["price"] = $row_inventory['price'];
$contents[$count]["quantity"] = $row['quantity'];
$contents[$count]["total"] = ($row_inventory['price'] * $row['quantity']);
$contents[$count]["description"] = $row_inventory['description'];
                                 $contents[$count]["title"] = $row_inventory['title'];
                                 $contents[$count]["author"] = $row_inventory['author'];
$count++;
}
return $contents;
}

function num_items()
{
                
$query = "SELECT * FROM cart WHERE session='".$this->get_sess()."' ";
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
return $num_rows;
}

function quant()
{
                
$query = "SELECT sum(quantity) as quantity FROM cart WHERE session='".$this->get_sess()."' ";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
return $row['quantity'];
}

                
}

class cart_output extends cart
{
/* Just a quick class for outputting the cart in a formatted way. Each function has a comment on what it does.
I recommend writting your own output methods as these are pretty messy and should just be treated a _really_ quick example
*/
function formatted_cart()
                {// Outputs a formatted table containing the contents of the cart and the appropriate links etc to modify quantity
$cart = new cart;
                 if($this->num_items() > 0)
                 {
                 $contents = $this->contents();
                 echo '<form action="index.php?action=recalc" method="post"><table width="100%"><tr><td>Quantity:</td><td>Title:</td><td>Price (Inc. Tax):</td><td>Sub-Total:</td><td></td></tr>';
                 foreach($contents as $contents)
                 {
                 echo '<tr><td><input type="text" name="quantity[]" size="5" value="'.$contents['quantity'].'"><input type="hidden" name="pid[]" value="'.$contents['pid'].'"></td><td>'.$contents['title'].'</td><td>$'.$contents["price"].'</td><td>$'.$contents["total"].'</td><td><a href="index.php?pid='.$contents['pid'].'&action=remove">Remove</a></td></tr>';
                 }
                 echo '<tr><td colspan="3" align="right">Sub-Total (Tax Total $'.($this->total() / 10).'):</td><td>$'.$this->total().'</td><td></td></tr></table><input name="recalc" type="hidden"><input name="submit" value="Recalculate Sub-Total" type="submit"></form>';
                 } else {
                 echo 'Your Shopping Cart is empty.<br><br>';
                 }
                 $this->list_cats();
                }
                function buy_box($pid, $price)
                {// Outputs a buy box to buy an item
                 ?>
                 <form name="form1" method="get" action="index.php">
                 <input type="submit" name="Submit" value="Add to cart"><br>
                 Qty:<input type="text" name="qty" size="5" value="1"><br>
         $<?=$price?><br>                
         <input name="action" type="hidden" value="add">
         <input name="pid" type="hidden" value="<?=$pid?>">

         </p>
</form>
         <?
                }
                
                function list_cats()
                {// Output categories
                
                 $result = mysql_query('select * from cat');

                 while ($row = mysql_fetch_array($result))
                 {
                 echo '[ <a href="index.php?cat='.$row['cid'].'">'.$row['name'].'</a> ]';
                 }
                }
                
                function prod_info()
                {// Outputs product information
                
                 $result = mysql_query('select product.author, product.title, product.description, product.price, cat.name, cat.cid from product, cat where product.cid = cat.cid and product.pid = '.$_GET['prod'].' limit 1');
                 $row = mysql_fetch_array($result);
                 echo 'Back to <a href="index.php?cat='.$row['cid'].'">'.$row['name'].'</a> <br><br>';
                 echo 'Title: '.$row['title'].'<br> Author: '.$row['author'].'<br> Description: '.$row['description']."\n";
                 $this->buy_box($_GET['prod'], $row['price']);
                }
                
                function list_products($cid)
                {// Lists products in a specific category.
                 GLOBAL $db, $admin;
                 $result = mysql_query('select * from product where cid = '.$cid);
                 echo '<table width="100%">';
                 echo "<tr><td>Title</td><td>Author</td><td>Price</td></tr>\n";
                 while ($row = mysql_fetch_array($result))
                 {
                 echo '<tr><td><a href="index.php?action=viewprod&prod='.$row['pid'].'">'.$row['title'].'</td><td>'.$row['author'].'</td><td>';
                 $this->buy_box($row['pid'], $row['price']);
                         if($admin)
                         {
                                 echo '<br><a href="admin.php?action=edit_prod&pid='.$row['pid'].'">Edit Product</a>
                                        <br><a href="admin.php?pid='.$row['pid'].'&action=remove">Remove Product</a>';
                         }
                 echo '</td></tr>';
                 }
                 echo '</table>';
                }
}
/*
//EXAMPLE OF USING the cart_output class.

// YOU WILL HAVE TO DO THE CONNECTING TO THE MYSQL DATABASE SERVER HERE!!!

require "cart.class.php";// Shopping cart functions
$cart = new cart_output;

$admin = true;
if(isset($_GET['action'])){
if($_GET['action'] == "add")
{
if(isset($_GET['pid']) && isset($_GET['qty']))
{
$cart->add($_GET['pid'], $_GET['qty']);
}
$cart->formatted_cart();
} elseif($_GET['action'] == "remove")
{
if(isset($_GET['pid']))
{
$cart->remove($_GET['pid']);
}
$cart->formatted_cart();
}

elseif($_GET['action'] == "recalc")
{
$i=0;
foreach($cart->contents() as $contents)
{
$cart->modify_quantity($_POST['pid'][$i], $_POST['quantity'][$i++]);
}
$cart->formatted_cart();
}
elseif($_GET['action'] == "view")
{
$cart->formatted_cart();
}
elseif($_GET['action'] == "viewprod")
{
if(isset($_GET['prod']))
{
$cart->prod_info();
} else {
echo 'product identification number was not supplied...';
}
}
} else {
if(isset($_GET['cat']))
{
$cart->list_products($_GET['cat']);
} else {
$cart->list_cats();

}
}
*/


/*
// SQL DUMP:
# phpMyAdmin MySQL-Dump
# version 2.5.0
# http://www.phpmyadmin.net/ (download page)
#
# Host: hs
# Generation Time: Sep 30, 2003 at 09:44 PM
# Server version: 3.23.52
# PHP Version: 4.3.1
# Database : `shoppingcart`
# --------------------------------------------------------

#
# Table structure for table `cart`
#
# Creation: Aug 11, 2003 at 08:44 AM
# Last update: Aug 11, 2003 at 08:44 AM
#

CREATE TABLE `cart` (
`cid` int(11) unsigned NOT NULL auto_increment,
`pid` int(11) unsigned NOT NULL default '0',
`quantity` int(11) unsigned NOT NULL default '0',
`session` varchar(32) NOT NULL default '',
PRIMARY KEY (`cid`)
) TYPE=MyISAM AUTO_INCREMENT=7 ;

#
# Dumping data for table `cart`
#

INSERT INTO `cart` VALUES (1, 4, 1, 'bdef89b197343c3fbaf9eaf81fc33d15');
INSERT INTO `cart` VALUES (2, 1, 1, 'bdef89b197343c3fbaf9eaf81fc33d15');
INSERT INTO `cart` VALUES (3, 5, 4, '30eef40e0f85317746bd9a08d392b28c');
INSERT INTO `cart` VALUES (4, 1, 3, '8641721c67403abff0d884e724702a98');
INSERT INTO `cart` VALUES (5, 2, 1, '8641721c67403abff0d884e724702a98');
INSERT INTO `cart` VALUES (6, 4, 6, '8641721c67403abff0d884e724702a98');
# --------------------------------------------------------

#
# Table structure for table `cat`
#
# Creation: Aug 11, 2003 at 08:44 AM
# Last update: Aug 11, 2003 at 08:44 AM
#

CREATE TABLE `cat` (
`cid` int(11) unsigned NOT NULL auto_increment,
`name` char(40) NOT NULL default '',
PRIMARY KEY (`cid`)
) TYPE=MyISAM AUTO_INCREMENT=3 ;

#
# Dumping data for table `cat`
#

INSERT INTO `cat` VALUES (1, 'books');
INSERT INTO `cat` VALUES (2, 'movies');
# --------------------------------------------------------

#
# Table structure for table `product`
#
# Creation: Aug 11, 2003 at 08:44 AM
# Last update: Aug 11, 2003 at 08:44 AM
#

CREATE TABLE `product` (
`pid` int(11) unsigned NOT NULL auto_increment,
`cid` int(11) unsigned NOT NULL default '0',
`author` varchar(255) NOT NULL default '',
`title` varchar(60) NOT NULL default '',
`description` text NOT NULL,
`price` float(4,2) NOT NULL default '0.00',
PRIMARY KEY (`pid`),
KEY `cid` (`cid`)
) TYPE=MyISAM AUTO_INCREMENT=5 ;

#
# Dumping data for table `product`
#

INSERT INTO `product` VALUES (2, 1, 'pil Apshankar, Sanjay Abraham, Jan Rosa, Allan Kent, Devon O\'Dell, Andy Chase, Imam Suyoto', 'Professional PHP 4 Multimedia Programming', 'Book about PHP 4 mutimedia programming', '45.00');
INSERT INTO `product` VALUES (3, 1, 'KaLuis, Argerich, Chris, Lea, Ken, Egervari, Matt, Anton, Charlie, Killian, Chris, Hubbard, James, Fuller', 'Professional PHP 4 XML', 'Book about php 4 xml programming', '10.00');
INSERT INTO `product` VALUES (4, 2, 'Stephan Steilberg', 'E.T.', 'A movie about an alien', '15.82');


*/
?>

No comments: