Juicy slices of pie code
This page is en route to being a tiny repository for code snippets. Please note that as I have only been coding for six months, these are purely for my reference & edumacation and may contain dreadful faux pas.
Obviously there will be a lot of cross pollination between sections as, for instance, MySQL queries in frugiworld are delivered by postman PHP.
The code samples are kept in text files and loaded into each page using an included function that adds line breaks and converts relevant characters into HTML entities. Some sections are still blank.
Choose your style (basic beta):

A basic class with functions to add, update and delete items, show cart, check inventory and clean user input. Some ideas for content, structure and code style were gleaned from online tutorials, such as the one at Sitepoint, for which I am grateful.
<?php
class Cart {
var $username = "username";
var $password = "password";
var $database = "cart";
var $hostname = "localhost";
var $products_table = "products";
var $items_table = "items";
var $cart_id;
// CONSTRUCTOR ---------------------------------------------------------------------------------------------
function __construct($cart_id) {
$this->dblink = mysql_connect($this->hostname, $this->username, $this->password);
mysql_select_db($this->database, $this->dblink);
$this->cart_id = $cart_id;
}
// ADD ITEM ------------------------------------------------------------------------------------------------
function additem ($product, $quantity) {
if ($quantity<1) return "Sorry the quantity cannot be less than one!";
$tempquantity=$quantity;
$qty = $this->check_in_cart($product); // is this item already in the cart? Use another class function to check.
// now check the inventory
$query = "SELECT product_inventory, product_name FROM " . $this->products_table .
" WHERE product_id='".$product."'";
$result = mysql_query($query, $this->dblink) or die(mysql_error());
$row=mysql_fetch_array($result);
if($quantity > $row['product_inventory']) return "Sorry we only have ".$row['product_inventory']. " of these items in stock. Please select a smaller quantity."; // insufficient inventory
mysql_free_result($result);
if($qty == 0) { // none in cart? Insert.
$query = "INSERT INTO "
.$this->items_table
." (session_id, product_id, product_qty) VALUES ('"
.$this->cart_id."','".$product."', '".$quantity."') ";
mysql_query($query, $this->dblink) or die(mysql_error());
} else { // already in cart? Update.
$quantity += $qty;
$query = "UPDATE ".$this->items_table.
" SET product_qty='".$quantity."' WHERE session_id='".$this->cart_id."'
AND product_id='".$product."' ";
mysql_query($query, $this->dblink);
}
$updated_inventory = $row['product_inventory'] - $tempquantity;
$query = "UPDATE ".$this->products_table.
" SET product_inventory = '".$updated_inventory."' WHERE product_id='".$product."' ";
mysql_query($query, $this->dblink) or die(mysql_error()); // update the inventory
$return_string = ($tempquantity>1) ? $tempquantity." ".$row['product_name']."s added to cart." :
$tempquantity." ".$row['product_name']." added to cart.";
return $return_string;
}
// UPDATE ITEM -----------------------------------------------------------------------------------------------------
function updateitem($product, $quantity) {
if($quantity <= 0)
{
return $this->deleteitem($product); // simply delete if qty <=0
}
else
{
// get the current quantity of this product in cart from the items table
$old_qty = $this->check_in_cart($product);
// now check the inventory
$query = "SELECT product_inventory FROM " . $this->products_table .
" WHERE product_id='".$product."'";
$result = mysql_query($query, $this->dblink) or die(mysql_error());
$row = mysql_fetch_array($result);
if($old_qty-$quantity+$row['product_inventory'] <0) return
"Sorry we only have ".$row['product_inventory']. " of these items in stock. Please select a smaller quantity."; // insufficient inventory
mysql_free_result($result);
$query = "UPDATE ".$this->items_table.
" SET product_qty='".$quantity."'
WHERE session_id='".$this->cart_id."'
AND product_id='".$product."' ";
mysql_query($query, $this->dblink) or die(mysql_error()); // update the items table
$difference = $old_qty-$quantity; // number to add back into inventory
$query = "UPDATE ".$this->products_table.
" SET product_inventory = product_inventory + '".$difference."'
WHERE product_id='".$product."' ";
mysql_query($query, $this->dblink) or die(mysql_error()); // update the inventory
return "You successfully updated the item quantity.";
}
}
// DELETE ITEM ----------------------------------------------------------------------------------------------------
function deleteitem($product) {
if (!is_numeric($product)) { return "You left the update field blank."; }
// get the current quantity from items table to add back into inventory
$add_to_inventory = $this->check_in_cart($product);
$query = "UPDATE ".$this->products_table. " SET product_inventory = product_inventory + '".$add_to_inventory."' WHERE product_id='".$product."' ";
mysql_query($query, $this->dblink) or die(mysql_error()); // update the inventory
// now delete the item from the items table; check it exists first.
$query = "SELECT item_id FROM ".$this->items_table." WHERE session_id='".$this->cart_id."' AND product_id='".$product."' ";
$result = mysql_query($query, $this->dblink) or die (mysql_error());
if (mysql_num_rows($result) < 1) return "The item you tried to delete was not in your cart. Are you messing with my query string, Domunki?";
$query = "DELETE FROM ".$this->items_table." WHERE session_id='".$this->cart_id."' AND product_id='".$product."' ";
mysql_query($query, $this->dblink) or die (mysql_error());
return "You successfully removed the item from your cart.";
}
// CHECK IF ITEM ALREADY IN CART; IF SO GET QTY --------------------------------------------------------------------------
function check_in_cart($product) {
$query = "SELECT product_qty FROM ".$this->items_table.
" WHERE session_id='".$this->cart_id."'
AND product_id='$product' ";
$result = mysql_query($query, $this->dblink) or die(mysql_error());
if(mysql_num_rows($result) != 0) // if in cart
{
$row = mysql_fetch_array($result);
return $row['product_qty'];
}
else return 0;
}
// SHOW CART -------------------------------------------------------------------------------------------------//
function showcart () {
// SELECT items.id, products.id, products.name, items.quantity, products.price, SUM (products.price *
// items.quantity) FROM items, products WHERE items.sessionid = cartid AND products.id = items.productid
// GROUP BY items.productid
$query = "SELECT ".$this->items_table.".item_id,".
$this->products_table.".product_id,".
$this->products_table.".product_name,".
$this->items_table.".product_qty,".
$this->products_table.".product_price,
SUM("
.$this->products_table.".product_price*"
.$this->items_table.".product_qty) AS subtotal
FROM "
.$this->items_table.",".$this->products_table."
WHERE ".$this->items_table.".session_id='".$this->cart_id."' AND "
.$this->products_table.".product_id = "
.$this->items_table.".product_id
GROUP BY "
.$this->items_table.".product_id";
// phew!
$result = mysql_query($query, $this->dblink) or die(mysql_error());
if (mysql_num_rows($result)==0) {
return false;
}
else
{ // bung the lot in an array to return
$itemlist=array();
for ($i=0; $itemlist[] = mysql_fetch_assoc($result); $i++);
array_pop($itemlist); // remove last array value, which for some reason is empty.
return $itemlist;
}
}
// EMPTY CART ------------------------------------------------------------------------------------------------
function emptycart() {
// first get all the product ids/qty from cart so we know what to add back to inventory
$query = "SELECT product_id, product_qty FROM ".$this->items_table.
" WHERE session_id='".$this->cart_id."'";
$result = mysql_query($query, $this->dblink) or die(mysql_error());
if (mysql_num_rows($result) == 0) return "Your cart is already empty.";
while($row = mysql_fetch_array ($result))
{
$qty = $row['product_qty'];
$id = $row['product_id'];
// loop through changing quantity for each
$query = "UPDATE ".$this->products_table.
" SET product_inventory = product_inventory + '".$qty."'
WHERE product_id = '".$id."'";
mysql_query($query, $this->dblink) or die(mysql_error());
}
// ---- now delete the items
$query = "DELETE FROM ".$this->items_table.
" WHERE session_id='".$this->cart_id."'";
mysql_query($query, $this->dblink) or die(mysql_error());
return "You emptied your cart.";
}
//CLEAN STRING ----------------------------------------------------
var $stringy;
function clean ($string) {
$this->stringy=trim(strip_tags($string));
if (get_magic_quotes_gpc()) { $this->stringy = stripslashes($this->stringy); }
return mysql_real_escape_string($this->stringy);
}
// -------------------------------------------------------------------
}
?>
Here is how I use the class on my view cart page:
<?php
session_start();
include ('xxxxxxxx.php'); // the class file above
if (!isset($_SESSION['cartID'])) {
$_SESSION['cartID'] = session_id();
}
$cartID = $_SESSION['cartID'];
$cart = new Cart($cartID); // you've no idea how much it pleased me to type this the first time
// ----------------------------------------------------------------------------------------------------------
// Deal with add and update items thru $_POST (cause they involve quantities from a form field)
// ----------------------------------------------------------------------------------------------------------
// print_r($_POST); handy for debugging
if (isset($_POST['action'])) // hidden field
{
$action = $cart->clean($_POST['action']);
switch ($action) {
case "additem":
$product_id = $cart->clean($_POST['product_id']);
$quantity = $cart->clean($_POST['quantity']);
$message = ($cart->additem($product_id, $quantity));
break;
case "updateitem":
foreach($_POST as $key => $value) {
if (preg_match("/quantity/",$key) && $value<>"") { // find the quantityX field with a value
$quantity = $cart->clean($value);
$product_id = $cart->clean(substr($key, 8)); // each input field has a different name quantity1, quantity5 etc. and the number corresponds to the product_id, so we grab the number off the end.
} // end if
} // end foreach
$message = ($cart->updateitem($product_id, $quantity));
break;
}
} // end if isset POST
//--------------------------------------------------------------------------------------------
// deal with empty whole cart and delete single items with $_GET (no quantities involved)
// -------------------------------------------------------------------------------------------
if (isset($_GET['action']))
{
$action = $cart->clean($_GET['action']);
if (isset($_GET['product_id']))
{
$product_id = $cart->clean($_GET['product_id']);
}
switch ($action) {
case "emptycart":
$message = $cart->emptycart();
break;
case "deleteitem":
$message = $cart->deleteitem($product_id);
break;
}
} // end isset if GET -------------------------------------------------------------------------
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link href="cart.css" rel="stylesheet" type="text/css" />
<title>View Cart</title>
</head>
<body>
<div id="wrapper">
<h1>View Cart</h1>
<div class="table_contents">
<form action="viewcart.php" method="post">
<table cellpadding="0" cellspacing="0" summary="Cart contents">
<tr>
<th scope="col">Product ID</th>
<th scope="col">Name</th>
<th scope="col">Qty</th>
<th scope="col">Price each</th>
<th scope="col">Subtotal</th>
<th scope="col">Action</th>
<th scope="col">Update Qty</th>
</tr>
<?php
$itemlist = $cart->showcart();
$total="0.00";
if ($itemlist == 0) {
echo "</table>"; }
else {
//print_r($itemlist);
foreach ($itemlist as $row)
{
echo "<tr><td>".
$row['product_id'].
"</td>
<td>".
$row['product_name'].
"</td>
<td>".
$row['product_qty'].
"</td>
<td>".
$row['product_price'].
"</td>
<td>".
$row['subtotal'].
"</td>
<td>".
"<a href=\"viewcart.php?action=deleteitem&product_id={$row['product_id']}\">Remove</a>".
"</td>
<td>
<input type=\"text\" name=\"quantity".$row['product_id']."\" size=\"3\" maxlength=\"4\"/>
<input type=\"submit\" name=\"submit\" value=\"go\"/>
</td>
</tr>";
$total+=$row['subtotal'];
}
echo "</table>";
echo "<input type=\"hidden\" name=\"action\" value=\"updateitem\" />"; }
?>
</form>
<p><?php echo "<strong>Cart total: £".$total."</strong>";?></p>
<?php if ($message<>"") echo "<p>".$message."</p>"; ?>
<p class="links">
<a href ="javascript:history.go(-1);">Back</a> |
<a href="catalogue.php">View Catalogue</a> |
<a href="viewcart.php?action=emptycart">Empty cart</a> |
<?php if ($itemlist<>0) echo"<a href=\"checkout.php\">Check out</a>";
else echo "Check out";?>
</p>
</div>
</div>
</body>
</html>