SimpleshoPHP

Detailed Analysis - Part 4

addtobag.php

This next bit of PHP code is different. For one thing, it does not display any HTML on the visitor's browser. All it does is update the database on the server.

We start out with our sanity check: if we are not provided with our session validator, we kick the visitor back to the main page:

<?
require_once("startme.inc");
if (! isset($_SESSION["xvalid"])) {
        header("Location: main.php");
        exit;
}
if (! $qty ) {
        header("Location: main.php");
        exit;
}

if (! $sku ) {
        header("Location: main.php");
        exit;
}

Okay, looks like we didn't scare our customer off with all those tests. Here is the moment we've all been waiting for: our first sale:

$buy = "INSERT INTO bag VALUES('$PHPSESSID', '$sku', '$qty')";

$buy_result = mysql_query($buy,$connection)
        or die ("Couldn't insert record!");

Woo hoo! Was it good for you, too? We're updating a new table, called "bag," and asking it to hold three very important pieces of data: the Session ID we've been using since we first touched the index page, the SKU for a book, and how many copies are in the order. Those are enough to make up our shopping cart, or as we call it, our "book bag."

While we're at it, let's make sure no one else gloms on to our one-of-a-kind copy of Skylark of Space by setting the "in stock" field down by one -- the browse page will only show items where the "in stock" is greater than zero:

$stoc = "UPDATE books SET stock = stock - $qty WHERE sku='$sku'";
$stk_result = mysql_query($stoc,$connection)
	or die ("Couldn't update inventory");

Note to self: If the cart is abandoned, we have to recover this SKU and add it back to our inventory! Since this item will no longer show up in the browse page, and the "addtobag" page does not appear in her browser, there should not be a problem with the visitor backing up to a prior page and inadvertently adding twelve copies of the same item to her cart. If that problem does arise, we'll have to whip up some code to prevent it.

To finish, the logical thing to do is display the newly created bookbag to our customer by doing an HTTP redirect:

 
header("Location: bookbag.php");
exit;
?>

Next... addtobag.php giveth, rmfmbag.php taketh away.


The Technical Walkthrough

Summary

Detailed descriptions

SimpleshoPHP Home


You are invited to post comments or questions on the SimpleshoPHP forum at SourceForge.net.

SourceForge.net Logo


Copyright 2003-2005, Kevin Martin, dba Brass Cannon Consulting.
The project "SimpleshoPHP" is Free Software, distributed
under the LGPL as described at opensource.org