WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDESPHP CLASSESCODE SEARCHARTICLES SEARCHPHP FORUMSPHP MANUALPHP FUNCTIONS LISTWEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search


Submit a code Example / Snippet Join us on FaceBook
Submit a code Example / Snippet Submit Your Code
Poker Tournaments Poker Tournaments
Poker Guide for Developers Poker Guide for Developers
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
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 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
פרייסז - השוואת מחירים בסופר
ZeroLag.com
Texas Holdem Poker Evangelists

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 : Example Shopping cart class
Categories : Ecommerce, PHP, PHP Classes Update Picture
JJ Harrison
Date : Sep 30th 2003
Grade : 3 of 5 (graded 13 times)
Viewed : 30934
File : No file for this code example.
Images : No Images for this code example.
Search : More code by JJ Harrison
Action : Grade This Code Example
Tools : My Examples List

Submit your own code examples  Submit your own code examples 
 

<?
/*
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');


*/
?>



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
a class for doing payments to a cybercash server
Categories : Ecommerce, Complete Programs, PHP Classes, PHP
an example of the cyberlib payment class
Categories : PHP, PHP Classes, Ecommerce, Credit Cards
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
simple shopping cart for php3
Categories : PHP, PHP Classes, Complete Programs, Ecommerce
Authorize.net AIM Interface Class v1.0.0
Categories : PHP, PHP Classes, Ecommerce, Payment Gateways
shopping cart class with add/edit/delete product functionality.
Categories : PHP, PHP Classes, Ecommerce
phpAds, a complete banner and ad management system with detailled tracking and stats.
Categories : MySQL, Complete Programs, Ecommerce, PHP, Databases
PHP5 URL Object
Categories : PHP, PHP Classes, URLs, Strings
Simple Template Class/Example
Categories : PHP, Templates, PHP Classes
Php Input Output Library - access the parallel and serial(rs232) port directly.
Categories : PHP, Hardware, PHP Classes
class formHTML build your HTML Forms from PHP
Categories : PHP, PHP Classes, HTML and PHP, HTML
PHP Based Apache + Mysql Error Log Parser
Categories : PHP, PHP Classes, Apache, MySQL, Log Files
News management class
Categories : PHP, PHP Classes, Beginner Guides
Generate HTML Calendar of a month of year
Categories : PHP, Calendar, PHP Classes