The Code

   

This section details the code involved in the script. The descriptions are of a high level, as most of the topics have already been covered. Additional descriptions are provided when new topics are introduced.

cart.sql

cart.sql is the SQL statement required to set up the database for use with this application.

Script 5-1 cart.sql
  1.  create table customers (  2.  id INT NOT NULL,  3.  first VARCHAR(32),  4.  mi CHAR(2),  5.  last VARCHAR(32),  6.  address1 VARCHAR(64),  7.  address2 VARCHAR(64),  8.  city VARCHAR(32),  9.  state CHAR(2), 10.  zip VARCHAR(10), 11.  country VARCHAR(32), 12.  shiptobilling VARCHAR(5), 13.  ship_address1 VARCHAR(64), 14.  ship_address2 VARCHAR(64), 15.  ship_city VARCHAR(32), 16.  ship_state CHAR(2), 17.  ship_zip VARCHAR(10), 18.  ship_country VARCHAR(32), 19.  ship_phone VARCHAR(32), 20.  email VARCHAR(128), 21.  PRIMARY KEY(id)); 22. 23.  create table order_details ( 24.  id int not null, 25.  orderid INT, 26.  code VARCHAR(32), 27.  qty INT, 28.  PRIMARY KEY(id)); 29. 30.  create table orders ( 31.  id INT not null, 32.  customer INT, 33.  status VARCHAR(16), 34.  tracking_number VARCHAR(128), 35.  PRIMARY KEY(id)); 36. 37.  create table inventory ( 38.  id INT not null, 39.  name VARCHAR(32), 40.  category INT, 41.  code VARCHAR(32), 42.  description TEXT, 43.  price VARCHAR(8), 44.  picture VARCHAR(128), 45.  qty INT, 46.  PRIMARY KEY(id)); 47. 48.  create table category ( 49.  id INT not null, 50.  name VARCHAR(128), 51.  description TEXT, 52.  PRIMARY KEY(id)); 

Script 5-1. cart.sql Line-by-Line Explanation

LINE

DESCRIPTION

1-21

Create a table to store customer data.

23-28

Create a table to store details of an order. Each item in an order has its own row in this table. The orderid column acts as a foreign key to the orders table.

30-35

Create a table to store the order. This table references the customer table for customer information, and holds that status and tracking information for the order.

37-46

Create a table to hold the data for each of the items in the inventory. The category column acts as a foreign key to the category table.

48-52

Create a table to store the category information.

cart.php

cart.php is the main script for the application. It references cart_inc.php for some additional shared functions.

Script 5-2 cart.php

[View full width]

  1.  <?  2.  require_once("include/cart_inc.php");  3.  session_start();  4.  session_register("items");  5.  session_register("category_choice");  6.  session_register("total");  7.  8.  if(!isset($items)) {  9.    $items = array(); 10.  } 11.  if(!isset($category_choice)) { 12.    $category_choice=1; 13.  } 14. 15.  /*************** MAIN ***************/ 16.  head(); 17.  $dbconn = connect(); 18.  select_cat(); 19.  $status = "shopping"; 20. 21.  ?> 22.  <table width="58%" border="1" cellspacing="10" cellpadding="10" height="371"  graphics/ccc.gifbordercolor="#0000FF" bgcolor="#999999"> 23.  <tr align="left" valign="top"> 24.  <td bgcolor="#CCCCCC" bordercolor="#0000FF"> 25.  <table border="0" cellpadding="10"><tr><td valign=top> 26.  <? 27.  if(isset($category_choice_in)) { 28.    $category_choice = $category_choice_in; 29.  } 30. 31.  if(isset($update_cart)) { 32.    foreach($items_in as $cat => $val) { 33.      foreach($items_in[$cat] as $id => $qty) { 34.        if($qty < 1) { 35.          unset($items_in[$cat][$id]); 36.        } 37.      } 38.    } 39.    $items = $items_in; 40.  } 41. 42.  if(isset($itemview)) { 43.    full_item($itemview); 44.  } else { 45.    display_items($category_choice,$items); 46.  } 47. 48.  if(isset($action)) { 49.    $items = alter_cart($cat, $items, $item, $action); 50.  } 51. 52.  ?> 53.  </td><td valign=top> 54.  <h3>Your Cart:</h3> 55.  <? 56.  if(isset($modify)) { 57.    edit_cart($items); 58.  } else { 59.    display_cart($items); 60.  } 61.  ?> 62.  <p> 63.  <? 64. 65.  if(sizeof($items) > 0) { 66.    $total = calculate_total($items); 67.    //print_r($items); 68.    ?> 69.    <p>Do you want to <a href="<?=SECURE_URL?>checkout.php"><b>Checkout</b></a>? 70.    <? 71.  } 72.  ?> 73.  </td></tr></table> 74.  </td> 75.  </tr> 76.  </table> 77.  </div> 78.  </body> 79.  </html> 

Script 5-2. cart.php Line-by-Line Explanation

LINE

DESCRIPTION

2

Require the cart_inc.php file to use the functions that it contains.

3

Start a session.

4-6

Register session variables to store the items in the cart, the current category that the user is browsing, and the total amount of the user's cart.

8-10

If the $items array has not been set yet, then initialize it.

11-13

If the user has not yet selected a category, then show the first category by default.

16

Call the head() function to display the opening HTML for the page. We do this now so that the session variables can be registered correctly.

17

Establish the connection to the database.

18

Execute the select_cat() function from cart_inc.php. This function lists the available categories to browse.

19

Set the $status variable to shopping. Later, we will change it to checkout.

21-25

Print out a table to hold the items and shopping cart.

27-29

Update the session variable $category_choice with the category the user is currently browsing.

31-40

If the user has updated the cart, then add or subtract the changes to the $items_in array. Then update the session variable $items with the current items in the user's cart.

42-46

If the user clicked on an item name in the item list, then display the full information for that item using the full_item() function from cart_inc.php. Else, display all the items in the category.

48-50

If one of the actions was taken (add or remove an item), then execute the alter_cart() function from cart_inc.php.

52-55

Print out some normal HTML for the page.

56-60

If the user clicked the bulk modify link on the cart, then execute the edit_cart() function from cart_inc.php, else display the cart using the display_cart() function.

61-63

Print out a <p> to make some space on the page.

65-71

If there are one or more items in the cart, then calculate the total by calling the calculate_total() function from cart_inc.php. Also, provide a checkout link.

For testing, you can uncomment line 67 to see what items are stored in the items array.

72-79

Close out the table and end the HTML for the page.

cart_inc.php

cart_inc.php holds the functions that do all the grunt work for cart.php. I've separated them out in this file to make it easier to customize the appearance of cart.php.

Script 5-3 cart_inc.php

[View full width]

   1.  <?   2.  define(SECURE_URL, "http://localhost/advancedphp/chapter05/");   3.  define(IMAGE_URL, "http://localhost/advancedphp/chapter05/images/");   4.  define(SHIPPING_COST, "7.00");   5.  define(COMPANY_NAME, "Widget Industrial Inc.");   6.  define(CREDIT_AUTH_URL, "finishorder.php");   7.  define(COMPANY_EMAIL, "company@example.com");   8.   9.  function connect() {  10.    ini_set("include_path", "G:\apache\Apache\php\pear");  11.    require_once("DB.php");  12.    $type = "mysql";  13.    $username = "php";  14.    $password = "password";  15.    $host = "localhost";  16.    $database = "cart";  17.    $dsn = $type . "://" . $username . ":" . $password . "@" . $host . "/" . $database;  18.    $dbconn = DB::connect($dsn);  19.    errortrap($dbconn);  20.    $dbconn->setFetchMode(DB_FETCHMODE_ASSOC);  21.    return $dbconn;  22.  }//end connect  23.  24.  function errortrap($result) {  25.    if(DB::isError($result)) {  26.      ?><h3>There was an error!</h3><?  27.      die($result->getMessage());  28.    }  29.  } //end errortrap  30.  31.  function alter_cart($cat, $items, $item, $action) {  32.    global $dbconn;  33.    $sql = "select * from inventory where id = '$item' AND category =  '$cat'";  34.    $result = $dbconn->query($sql);  35.    errortrap($result);  36.    if($result->numRows() > 0) {  37.      switch($action) {  38.        case("add"):  39.          if(!isset($items[$cat][$item])) {  40.            $items[$cat][$item] = 0;  41.          }  42.          $items[$cat][$item]++;  43.          break;  44.        case("remove"):  45.          if(isset($items[$cat][$item])) {  46.            $items[$cat][$item]--;  47.          }  48.          if($items[$cat][$item] < 1) {  49.            unset($items[$cat][$item]);  50.          }  51.          break;  52.        default:  53.          break;  54.      }  55.    }  56.      return $items;  57.  } //end alter_cart  58.  59.  function full_item($item, $items) {  60.    global $dbconn;  61.    $sql = "select * from inventory where id = $item";  62.    $result = $dbconn->query($sql);  63.    errortrap($result);  64.    $result->fetchinto($r);  65.    ?>  66.    <table border=1 cellpadding=5 cellspacing=0>  67.    <tr><td class=tablehead><?=$r["name"]?></td></tr>  68.    <tr><td><?=$r["name"]?><br><?=$r["description"]?>  69.    <br><b>Price</b>: <?=$r["price"]?>  70.    <p>  71.    <?  72.    if($r["picture"] != "") {  73.      ?><div align="center"><img src="/books/2/160/1/html/2/<? echo IMAGE_URL . $r["picture"]?>"></div><?  74.    }  75.    if($r["qty"] > 1) {  76.      ?>  77.      <p><div align=center><a href="<?=SECURE_URL?>cart. graphics/ccc.gifphp?cat=<?=$r["category"]?>&item=<?=$item?>&itemview=<?=$item?>&action=add"><img  graphics/ccc.gifsrc="/books/2/160/1/html/2/<?=IMAGE_URL?>add.gif" border=0></a>  78.      <?  79.    } else {  80.      ?>  81.      <p>Sorry, Out Of Stock</p>  82.      <?  83.    }  84.    ?>  85.    <br><a href="<?=SECURE_URL?>cart.php">Return To List Of Items In This Category</a></ graphics/ccc.gifdiv></td></tr>  86.    </table>  87.    <?  88.  } //end function full_item  89.  90.  function build_menu ($ref, $table) {  91.      global $dbconn;  92.  $sql = "select * from $table order by id";  93.  $result = $dbconn->query($sql);  94.      errortrap($result);  95.      if($result->numRows() > 0) {  96.        $x = 0;  97.          while($result->fetchInto($r)){  98.            if($x == 0) {  99.                     echo '<option value="' . $r["id"] . '" selected>' . $r[$ref] . '</ graphics/ccc.gifoption>'; 100.                $x++; 101.            } else { 102.              echo '<option value="' . $r["id"] . '">' . $r[$ref] . '</option>'; 103.            } 104.  } 105.  } else { 106.          echo '<option value="">NO CATEGORIES DEFINED</option>'; 107.  } 108.  } //end build_menu 109. 110.  function head() { 111.    ?> 112.    <html> 113.    <head> 114.    <style type=text/css> 115.    h1, h2, h3, p, td {font-family: verdana, sans-serif; } 116.    .tablehead {font-size: 12pt; color: #FFFFFF; background-color: #000099; } 117.    .required {font-weight: bold; color: red; } 118.    .smalli {font-size: 8pt; font-style: italic;} 119.    </style> 120.    </head> 121.    <body bgcolor="#FFFFFF"> 122.    <div align=center> 123.    <table width="74%" border="0" cellspacing="0" cellpadding="0" height="128"  graphics/ccc.gifbgcolor="#FFFFFF"> 124.  <tr> 125.  <td height="134" align="center"><h1>A Simple Shopping Cart</h1></td> 126.  </tr> 127.  </table> 128.    <? 129.  } 130. 131.  function calculate_total($items) { 132.      global $dbconn; 133.    $shipping = SHIPPING_COST; 134.    $total = 0; 135.    foreach($items as $key => $val) { 136.      foreach($items[$key] as $key2 => $val2) { 137.        $sql = "select * from inventory where id = '$key2'"; 138.        $result = $dbconn->query($sql); 139.        errortrap($result); 140.        $result->fetchinto($r); 141.        $total+= ($r["price"] * $val2); 142.      } 143.    } 144.    if($total != 0) { 145.      $total = $total + $shipping; 146.    } 147.    return $total; 148.  } //end calculate_total 149. 150.  function display_cart($items) { 151.    global $dbconn; 152.    global $items, $status; 153.    $shipping = SHIPPING_COST; 154.    $count = 0; 155.    ?> 156.    <table border=1 cellpadding=5 cellspacing=0> 157.    <tr><td class=tablehead>Name</td><td class=tablehead>Qty</td><td  graphics/ccc.gifclass=tablehead>Price Each</td><td class=tablehead>&nbsp;</td></tr> 158.    <? 159.    foreach($items as $cat => $val) { 160.      foreach($items[$cat] as $item => $qty) { 161.        $sql = "select * from inventory where id = '$item'"; 162.        $result = $dbconn->query($sql); 163.        errortrap($result); 164.        $result->fetchinto($r); 165.        ?> 166.        <tr><td><?=$r["name"]?></td><td><?=$qty?></td><td><?=$r["price"]?></td> 167.        <? 168.        if($status == "checkout") { 169.          echo "<td>&nbsp;</td>"; 170.        } else { 171.          ?> 172.          <td><a href="<?=SECURE_URL?>cart. graphics/ccc.gifphp?cat=<?=$r["category"]?>&item=<?=$r["id"]?>&action=remove"> 173.          <img src="/books/2/160/1/html/2/<?=IMAGE_URL?>remove.gif" border=0></a></td> 174.          <? 175.        } 176.        ?> 177.        </tr> 178.        <? 179.        $count++; 180.      } 181.    } 182.    if($count == 0) { 183.      $items= array(); 184.      ?> 185.      <tr><td colspan=4><h3>Your Cart Is Empty!</h3></td><tr> 186.      <? 187. 188.    } 189.    $total = calculate_total($items); 190.    ?> 191.    <tr><td colspan=3>Shipping and Handling</td><td><?=$shipping?></td></tr> 192.    <tr><td class=smalli> 193.    <? 194.    if($status != "checkout") { 195.      if($count > 0) { 196.        ?>Click <a href=<?=SECURE_URL?>cart.php?modify=bulk">HERE</a> to modify  graphics/ccc.gifbulk<br>quantities in your cart.<? 197.      } 198.    } 199.    ?> 200.    &nbsp;</td><td colspan="2" align="right">Total:</td><td> 201.    <? 202.    printf("%.2f", $total); 203.    ?></td></tr></table><? 204.  }//end display_cart 205. 206.  function cart2form($items) { 207.  foreach($items as $cat => $val) { 208.  foreach($val as $item => $qty) { 209.  ?> 210.  <input type="hidden" name="cart[<?=$item; ?>]" value="<?=$qty; ?>"> 211.  <? 212.  } 213.  } 214.  }//end cart2form 215. 216.  function display_items($cat, $items) { 217.    global $dbconn; 218.    $sql = "select * from inventory where category = '$cat'"; 219.    $result = $dbconn->query($sql); 220.    errortrap($result); 221.    if($result->numRows() > 0) { 222.      ?> 223.      <h2>Available Items In This Category:</h2> 224.      <table border=1 cellpadding=5 cellspacing=0> 225.      <tr><td class=tablehead>Name <div class=smalli>click name for details</div></td><td  graphics/ccc.gifclass=tablehead>Price</td><td class=tablehead>&nbsp;</td></tr> 226.      <? 227.      while($result->fetchinto($r)) { 228.          ?> 229.        <tr><td><a href="<?=SECURE_URL?>cart.php?itemview=<?=$r["id"]?>"><?=$r["name"]?></ graphics/ccc.gifa></td> 230.        <td><?=$r["price"]?></td> 231.        <td> 232.        <? 233.        if($r["qty"] > 1) { 234.          ?> 235.          <a href="<?=SECURE_URL?>cart. graphics/ccc.gifphp?cat=<?=$r["category"]?>&item=<?=$r["id"]?>&action=add"><img src="/books/2/160/1/html/2/<?=IMAGE_URL?>add. graphics/ccc.gifgif" border=0></a> 236.          <? 237.        } else { 238.          ?> 239.          Out Of Stock 240.          <? 241.        } 242.        ?> 243.        </td></tr> 244.        <? 245.      } 246.      ?> 247.      </table> 248.      <? 249.    } else { 250.      echo "<h3>Select A Category Above</h3>"; 251.    } 252.  } //end display_items 253. 254.  function edit_cart($items) { 255.      global $dbconn; 256.    ?> 257.    <form action=cart.php method=post> 258.    <table border=1 cellpadding=5 cellspacing=0> 259.    <tr><td class=tablehead>Name</td><td class=tablehead>Price Each</td><td  graphics/ccc.gifclass=tablehead>Qty</td></tr> 260.    <? 261.    foreach($items as $cat => $val) { 262.      foreach($items[$cat] as $item => $qty) { 263.        $sql = "select * from inventory where id = '$item'"; 264.        $result = $dbconn->query($sql); 265.        errortrap($result); 266.        $result->fetchinto($r); 267.        ?> 268.        <tr><td><?=$r["name"]?></td><td><?=$r["price"]?></td> 269.        <td> 270.        <input type="text" name="items_in[<?=$cat?>][<?=$item?>]" value="<?=$qty?>"  graphics/ccc.gifsize="3"> 271.        </td></tr> 272.        <? 273.      } 274.    } 275.    ?> 276.    </table> 277.    <input type="submit" name="update_cart" value="Update Cart"> 278.    </form> 279.    <? 280.  } //end edit_cart 281. 282.  function select_cat() { 283.    ?> 284.    <form action=cart.php method=post> 285.    <p>Select Category to Shop: <select name="category_choice_in"> 286.    <? build_menu("name","category"); ?> 287.    </select> 288.    <input type="submit" name="submit" value="Submit"> 289.    </form> 290.    <? 291.  } //end select_cat 292.  ?> 

Script 5-3. cart_inc.php Line-by-Line Explanation

LINE

DESCRIPTION

2-7

Create some constants. Fill in the values as applicable to your site. Since this cart assumes a flat shipping rate, I've also specified the shipping cost here so that it can be easily changed.

9-22

Use a PEAR DB connect function to create a connection to the database.

24-29

Create a short error trapping function to check for PEAR DB errors after every query. This can be customized to suit your reporting needs. Error reporting is covered in detail in Chapter 8.

31-57

Define a function, alter_cart(), to add and remove items from the user's shopping cart.

The items array is actually a two-dimensional array. Each element in the items array is an array itself. The top-level arrays are categories. The arrays within them are item arrays. The structure looks like this:

  • items[category[cat1], category[cat2], category[cat3]]

  • cat1[item1[qty], item2[qty], item3[qty]]

  • cat2[item1[qty], item2[qty], item3[qty]]

  • cat3[item1[qty], item2[qty], item3[qty]]

59-88

Define a function, full_item(), to display the full description and option picture of an item. Users are also able to add items to the cart when they are viewing the full description.

90-108

Define a function, $build_menu, to use as a "helper function." This function simply creates a drop-down menu for use in other functions.

110-129

Define a function, head(), to display the opening HTML for a page.

131-141

Define a function, calculate_total(), to determine the total cost of the items in the shopping cart.

150-204

Define a function, $display_cart(), that displays the items in the shopping cart to the users. This function serves a couple of purposes. First, users can easily see what items are in their shopping cart. Second, users can easily remove items with the click of a button.

206-214

Define a function, cart2form(), that extracts the items in the user's cart and places them in hidden form fields. This is used on the checkout.php page.

216-252

Define a function, display_items(), to display the list of items in a given category. In addition to displaying the items, this function also provides a button to add items to a user's cart and a link to see the full description of an item.

254-280

Define a function, edit_cart(), that allows the users to "bulk modify" items in their carts by specifying a quantity of items instead of having to click the "Add" button numerous times.

282-291

Define a function, select_cat(), that prints out a short form so that the user may select a category to browse.

292

End the PHP for the page.

dbmanage.php

dbmanage.php is used to manage the categories and items in the inventory.

Script 5-4 dbmanage.php

[View full width]

   1. <?   2. require_once("../include/cart_inc.php");   3.   4. function add($item, $HTTP_POST_VARS) {   5.   global $dbconn;   6.   if($item == "cat") {   7.     $id = $dbconn->nextID('category',true);   8.     $sql = "insert into category values ('$id', '" . $HTTP_POST_VARS["name"] . "','" .  graphics/ccc.gif$HTTP_POST_VARS["description"] . "')";   9.    } elseif($item == "item") {  10.     $id = $dbconn->nextID('inventory',true);  11.     $sql = "insert into inventory VALUES('$id', '" .  12.      $HTTP_POST_VARS["name"] . "','" .  13.      $HTTP_POST_VARS["category"] . "','" .  14.      $HTTP_POST_VARS["code"] . "','" .  15.      $HTTP_POST_VARS["description"] . "','" .  16.      $HTTP_POST_VARS["price"] . "','" .  17.      $HTTP_POST_VARS["picture"] . "','" .  18.      $HTTP_POST_VARS["qty"] . "')";  19.    } else {  20.      return 0;  21.    }  22.    $result = $dbconn->query($sql);  23.    errortrap($result);  24.    return 1;  25. } //end add  26.  27. function display($item, $cat) {  28.   global $dbconn;  29.   if($item == "cat") {  30.     $sql = "select * from categories order by name";  31.   } elseif($item == "item") {  32.     $sql = "select * from inventory order by category, name";  33.   } else {  34.     return 0;  35.   }  36.   $result = $dbconn->query($sql);  37.   errortrap($result);  38.   ?>  39.   <p>  40.   <table border=1 cellpadding=5>  41.   <?  42.   if($item == "item") {  43.     ?><tr class=tablehead><td>Name</td><td>Code</td><td>Description</td><td>Price</ graphics/ccc.giftd><td>Picture</td><td>Qty</td></tr><?  44.   } else {  45.     ?><tr class=tablehead><td>Name</td><td>Description</td></tr><?  46.   }  47.   while($result->fetchinto($r)) {  48.     if($item == "cat") {  49.       ?>  50.       <tr><td><?=$r["name"]?></td><td><?=$r["description"]?></td></tr>  51.     <?  52.     } elseif($item == "item") {  53.       ?>  54.       <tr><td><?=$r["name"]?></td><td><?=$r["code"]?></td><td><?=$r["description"]?></td>  55.       <td><?=$r["price"]?></td><td><?=$r["picture"]?>&nbsp;</td>  56.       <td><?=$r["qty"]?></td>  57.       </tr>  58.       <?  59.     }  60.  }  61.  ?></table><?  62. }// end display  63.  64. function item_edit($cat, $limit) {  65.      global $dbconn;  66.          $sql = "select * from inventory where category = '$cat' order by id limit  graphics/ccc.gif$limit,20";  67.        $result = $dbconn->query($sql);  68.      errortrap($result);  69.       if($result->numRows() > 0) {  70.          ?>  71.        <p>Viewing inventory items <?=$limit?> through <?=($limit+=20) ?>.  72.        <form action=dbmanage.php method=post>  73.        <input type=hidden name="category" value="<?=$cat?>">  74.        <input type=hidden name=limit value="<?=$limit ?>">  75.        <input type="submit" name="choose_cat" value="View Next 20">  76.        </form>  77.            <table>  78.            <tr class=tablehead><td>Name</td><td>Category</td><td>Code</ graphics/ccc.giftd><td>Description</td><td>Price</td><td>Picture</td><td>Qty</td><td>Action</td>  79.            <?  80.        while($result->fetchinto($r)){  81.                    ?>  82.                    <form action=dbmanage.php method=post>  83.                    <input type=hidden name=id value="<?=$r["id"]?>">  84.            <input type=hidden name=limit value="<?=$limit ?>">  85.                    <tr>  86.                            <td><input type=text name=name value="<?=$r["name"]?>"></td>  87.                            <td>  88.                                    <select name="category">  89.                                            <? build_menu("name","category"); ?>  90.                                    </select>  91.                            </td>  92.                            <td><input type=text name=code value="<?=$r["code"]?>"></td>  93.                            <td><textarea name=description cols=15  graphics/ccc.gifrows=2><?=$r["description"]?></textarea></td>  94.                            <td><input type=text name=price value="<?=$r["price"]?>"></td>  95.                            <td><input type=text name=picture  graphics/ccc.gifvalue="<?=$r["picture"]?>"></td>  96.                            <td><input type=text name=qty value="<?=$r["qty"]?>"></td>  97.                            <td><input type="submit" name="submit" value="Update  graphics/ccc.gifItem"><input type="submit" name="submit" value="Delete Item"></td>  98.                    </form>  99.                    <? 100.            } 101.            ?></table><? 102.      } else { 103.        ?> 104.        <h2>There are no more items in this category</h2> 105.        <? 106.      } 107.  }//end item_edit 108. 109.  function process_item_edit ($HTTP_POST_VARS) { 110.      global $dbconn; 111.      $delete_cat_items = "false"; 112.          if($HTTP_POST_VARS["submit"] == "Delete Item") { 113.                  $sql = "delete from inventory where id = '" . $HTTP_POST_VARS["id"] .  graphics/ccc.gif"'"; 114.          } elseif($HTTP_POST_VARS["submit"] == "Update Item") { 115.                  $sql = "update inventory set name='" . $HTTP_POST_VARS["name"] . "',  graphics/ccc.gifcategory='" .$HTTP_POST_VARS["category"] . 116.                                  "', code='" . $HTTP_POST_VARS["code"] ."',  graphics/ccc.gifdescription='" . 117.                                  $HTTP_POST_VARS["description"] . "', price='" .  graphics/ccc.gif$HTTP_POST_VARS["price"]  . 118.                                  "', picture ='" . $HTTP_POST_VARS["picture"] . "',  graphics/ccc.gifqty='" . $HTTP_POST_VARS["qty"] . 119.                                  "' where id='" . $HTTP_POST_VARS["id"] . "'"; 120.          } elseif($HTTP_POST_VARS["submit"] == "Delete Category") { 121.        $sql = "delete from category where id = '" . $HTTP_POST_VARS["id"] . "'"; 122.        $delete_cat_items = "true"; 123.      } elseif($HTTP_POST_VARS["submit"] == "Update Category") { 124.        $sql = "update category set name='" . $HTTP_POST_VARS["name"] ."', description='" . 125.                                  $HTTP_POST_VARS["description"] . "' where id='" .  graphics/ccc.gif$HTTP_POST_VARS["id"] . "'"; 126.      } 127.          $result = $dbconn->query($sql); 128.          errortrap($result); 129.                  echo "<h2>" . $HTTP_POST_VARS["submit"] . " Successful!</h2>\n"; 130.      if($delete_cat_items == "true") { 131.            $sql2 = "delete from inventory where category = '" . $HTTP_POST_VARS["id"] .  graphics/ccc.gif"'"; 132.            $result = $dbconn->query($sql2); 133.            errortrap($result); 134.            //} 135.      } 136.  } //end process_item_edit 137. 138.  function cat_edit() { 139.      global $dbconn; 140.          $sql = "select * from category order by id "; 141.      $result = $dbconn->query($sql); 142.      errortrap($result); 143.       if($result->numRows() > 0) { 144.        ?> 145.        <p>Viewing Categories: 146.            <table> 147.            <tr class=tablehead><td>Name</td><td>Description</td><td>Action</td></tr> 148.            <? 149.           // while($r = mysql_fetch_array($result)) { 150.         while($result->fetchinto($r)) { 151.                    ?> 152.                    <form action=dbmanage.php method=post> 153.                    <input type=hidden name=id value="<?=$r["id"]?>"> 154.                    <tr> 155.                            <td><input type=text name=name value="<?=$r["name"]?>"></td> 156.                            <td><textarea name=description cols=25  graphics/ccc.gifrows=5><?=$r["description"]?></textarea></td> 157.                            <td><input type="submit" name="submit" value="Update  graphics/ccc.gifCategory"><input type="submit" name="submit" value="Delete Category"></td> 158.                    </form> 159.                    <? 160.            } 161.      } else { 162.        ?> 163.        <h2>There are no categories to edit!</h2> 164.            </table> 165.        <? 166.      } 167.  }//end cat_edit 168. 169.  function add_cat_form() { 170.    ?> 171.    <form action=dbmanage.php method=post> 172.      <table border="1" cellspacing="0" cellpadding="5"> 173.      <tr class=tablehead> <td colspan="2"><h2>Add A Category</h2></td></tr> 174.      <tr><td>Name</td><td><input type="text" name="name" size="32" maxlength="32"></td></ graphics/ccc.giftr> 175.      <tr><td>Description</td><td><textarea name="description" cols=30 rows=5></ graphics/ccc.giftextarea></td></tr> 176.      <tr><td colspan="2"> <input type="submit" name="add_cat" value="Add Category"></ graphics/ccc.giftd></tr> 177.      </table> 178.     </form> 179.    <? 180.  }//end add_cat_form 181. 182.  function add_item_form() { 183.    ?> 184.    <form action=dbmanage.php method=post> 185.      <table border="1" cellspacing="0" cellpadding="5"> 186.      <tr class=tablehead> <td colspan="2"><h2>Add An Inventory Item</h2></td></tr> 187.      <tr><td>Name</td><td><input type="text" name="name" size="32" maxlength="32"></td></ graphics/ccc.giftr> 188.      <tr><td>Category</td><td><select name="category"> <? build_menu("name","category");  graphics/ccc.gif?></select></td></tr> 189.      <tr><td>Code</td><td><input type="text" name="code" size="32" maxlength="32"></td></ graphics/ccc.giftr> 190.      <tr><td>Description</td><td><textarea name="description" cols=30 rows=5></ graphics/ccc.giftextarea></td></tr> 191.      <tr><td>Price</td><td><input type="text" name="price" size="8" maxlength="8"></td></ graphics/ccc.giftr> 192.      <tr><td>Picture</td><td><input type="text" name="picture"></td></tr> 193.      <tr><td>Qty In Stock</td><td><input type="text" name="qty" size="5"></td></tr> 194.      <tr><td colspan="2"> <input type="submit" name="add_item" value="Add Item"></td></ graphics/ccc.giftr> 195.      </table> 196.    </form> 197.    <? 198.  }//end add_item_form 199. 200.  function choose_cat_form() { 201.    ?> 202.    <form action=dbmanage.php method=post> 203.      <select name="category"> 204.            <? build_menu("name","category"); ?> 205.      </select> 206.       <input type="submit" name="choose_cat" value="Edit Items In This Category"> 207.    </form> 208.    <? 209.  }//end choose_cat_from 210. 211. 212.  function edit_cats_form() { 213.    ?> 214.    <form action=dbmanage.php method=post> 215.      <input type="submit" name="edit_cat" value="Edit All Categories"> 216.    </form> 217.    <? 218.  } 219. 220. 221.  function choices() { 222.    ?> 223.    <table border=1 cellpadding=5 cellspacing=0> 224.      <tr valign="middle"><td><a href=dbmanage.php?action=addcat>Add A Category</a></ graphics/ccc.giftd><td><a href=dbmanage.php?action=additem>Add An Item</a></td><td> 225.      <a href=dbmanage.php?action=display>Display Inventory</a></ graphics/ccc.giftd><td><?=choose_cat_form()?></td><td><?=edit_cats_form()?></td></tr> 226.    </table> 227.    <? 228.  }//end_choices 229. 230.  /***** MAIN *****/ 231.  head(); 232.  $dbconn = connect(); 233.  if(isset($submit)) { 234.    process_item_edit($HTTP_POST_VARS); 235.  } 236.  if(isset($add_cat)) { 237.    if(!add("cat", $HTTP_POST_VARS)) { 238.      echo "Error adding cat!"; 239.    } else { 240.      echo "<h2>Added New Category</h2>"; 241.    } 242.  } 243.  if(isset($add_item)) { 244.    if(!add("item", $HTTP_POST_VARS)) { 245.      echo "Error adding item!"; 246.    } else { 247.      echo "<h2>Added New Item</h2>"; 248.    } 249.  } 250.  choices(); 251.  if(isset($action)) { 252.    if($action == "addcat") { 253.      add_cat_form(); 254.    }elseif($action == "additem") { 255.      add_item_form(); 256.    }elseif($action == "display") { 257.      display("item","1"); 258.    } 259.  } 260.  if(isset($choose_cat)) { 261.    if(!isset($HTTP_POST_VARS["limit"])) { 262.      $HTTP_POST_VARS["limit"] = 0; 263.    } 264.    item_edit($category, $HTTP_POST_VARS["limit"]); 265.  } 266.  if(isset($edit_cat)) { 267.    cat_edit();v 268.  } 269.  ?> 270.  </body> 271.  </html> 

Script 5-4. dbmanage.php Line-by-Line Explanation

LINE

DESCRIPTION

2

Require cart_inc.php because it contains some functions used by this script.

4-25

Define a function, add(), which adds a category or an item to the inventory. This function uses the PEAR DB function nextID() to generate an auto-increment ID:

 $dbconn->nextID($table, $create); 

nextID takes two arguments:

  • $table The table for which the ID is to be generated.

  • $create A boolean value, set to true if it should start an ID sequence if one does not already exist.

The nextID() function solves the problem for those of us who like to use the auto_increment feature to create IDs in MySQL, but who also want the application to be used on different databases, some of which do not use the auto_increment feature for IDs.

27-62

Define a function, display(), that displays the items in the inventory.

64-107

Define a function, item_edit(), to print a form to edit an existing item in the inventory. This function displays multiple items at once, 20 items at a time.

109-136

Define a function, process_item_edit(), to process the changes made by using the item_edit() function. If a category is deleted, then all of the items associated with that category are also deleted.

138-167

Define a function, cat_edit(), to print a form to edit an existing category.

169-180

Define a function, add_cat_form, to print a form to add a new category.

182-198

Define a function, add_item_form(), to print a form to add a new item.

200-218

Define a function, choose_cat_form(), to print a form allowing the user to choose a category to edit.

221-228

Define a function, choices(), that displays the different actions the user can take to manage the inventory.

230

Begin the main program.

231

Use the head() function to print out the beginning HTML for the page.

232

Establish a connection to the database.

233-235

If the "Submit" button has been pushed, then execute the process_item_edit() function. The $submit button is mapped to all of the edit features on this page.

236-242

If the $add_item variable is set, then attempt to add a new item. If there was an error, then print out a message to the screen (most likely the script will die before this, because the error trap should catch it). If there was no error, then inform the user that the new item was added.

243-249

If the $add_cat variable is set, then attempt to add a new category. If there was an error, then print out a message to the screen (most likely the script will die before this, because the error trap should catch it). If there was no error, then inform the user that the new category was added.

250

Execute the choices() function to display these features to the user.

251-259

If the $action variable is set, then we know the user has pushed one of the buttons for "Add Category," "Add Item," or "Display All Items," as defined in the choices() function. Execute the proper function for the button (or link) that was clicked.

260-265

If the $choose_cat variable is set, then we know the user wished to view or edit the items in a particular category. Display the items in the category. Limit is used to view only 20 items at a time. If $limit is not set, then we know the user is on the first page, so set $limit to zero. The item_edit() function will increment limit each time the user views a subset of the data.

266-268

If the $edit_cat variable is set, then we know the user wishes to edit a category, so execute the cat_edit() function.

269

Close out the PHP and HTML for the page.

admin.php

admin.php is used to manage the orders that have been submitted.

Script 5-5 admin.php

[View full width]

   1.  <?   2.  function display_orders($mode) {   3.    global $dbconn;   4.    switch($mode) {   5.      case("all"):   6.        $sql = "select * from orders order by id";   7.        break;   8.      case("open"):   9.        $sql = "select * from orders where status = 'open' order by id";  10.        break;  11.      case("shipped"):  12.        $sql = "select * from orders where status = 'shipped' order by id";  13.        break;  14.      case("backorder"):  15.        $sql = "select * from orders where status = 'backorder' order by id";  16.        break;  17.      case("hold"):  18.        $sql = "select * from orders where status = 'hold' order by id";  19.        break;  20.      default:  21.        $sql = "select * from orders order by id";  22.        break;  23.    }  24.    $result = $dbconn->query($sql);  25.    errortrap($result);  26.    ?>  27.    <h3>Orders</h3>  28.    <table border=1 cellpadding=10 cellspacing=0>  29.    <tr><td  colspan=5><a href="admin.php?view=all">View All Orders</a> | <a href="admin. graphics/ccc.gifphp?view=open">View Open Orders</a> | <a href="admin.php?view=shipped">View Shipped  graphics/ccc.gifOrders</a> | <a href="admin.php?view=backorder">View Backorder Orders</a>  | <a  graphics/ccc.gifhref="admin.php?view=hold">View Hold Orders</a></td></tr>  30.    <tr><td>Order Number</td><td>Customer</td><td>Status</td><td>Tracking #</td><td>&nbsp; graphics/ccc.gif</td></tr>  31.    <?  32.    while($result->fetchinto($r)) {  33.      $r2 = get_customer($r["customer"]);  34.      ?>  35.      <tr>  36.        <td><a href="admin.php?display=orderdetails&id=<?=$r["id"]?>"><?=$r["id"]?></a></ graphics/ccc.giftd>  37.        <td><a href="admin.php?display=customer&id=<?=$r2["id"]?>"><?=$r2["last"]?>,  graphics/ccc.gif<?=$r2["first"]?></a></td>  38.        <td><?=$r["status"]?></td>  39.        <td><?=$r["tracking_number"]?> &nbsp;</td>  40.        <td><a href="admin.php?display=update&id=<?=$r["id"]?>">Update Order Status</a></ graphics/ccc.giftd>  41.      </tr>  42.      <?  43.    }  44.    ?>  45.    </table>  46.    <?  47.  } //end display_orders  48.  49.  function display_order_details($id) {  50.    global $dbconn;  51.    $sql = "select * from order_details where orderid = '$id'";  52.    $result = $dbconn->query($sql);  53.    errortrap($result);  54.    ?>  55.    <h2>Order Details For Order <?=$id?></h2>  56.    <h3>Items In Order</h3>  57.    <table border=1 cellpadding=10 cellspacing=0>  58.    <tr><td>Qty</td><td>Description</td></tr>  59.    <?  60.    while($result->fetchinto($r)) {  61.      ?>  62.      <tr>  63.        <td><?=$r["qty"]?> &nbsp;</td>  64.        <?  65.        $sql2 = "select * from inventory where id='" . $r["code"] . "'";  66.        $result2 = $dbconn->query($sql2);  67.        errortrap($result2);  68.        $result2->fetchinto($r2);  69.        ?>  70.        <td>  71.        name: <?=$r2["name"]?>  72.        <br>code: <?=$r2["code"]?>  73.        <br>description: <?=$r2["description"]?>  74.        <br>price: <?=$r2["price"]?>  75.        </td>  76.      </tr>  77.      <?  78.    }  79.    ?>  80.    </table>  81.    <?  82.    $sql = "select customer from orders where id = '$id'";  83.    $result = $dbconn->query($sql);  84.    errortrap($result);  85.    $result->fetchinto($r);  86.    $cust = get_customer($r["customer"]);  87.    display_customer($cust);  88.  } //end display_order_details  89.  90.  function update_order_status($id) {  91.    global $dbconn;  92.    $sql = "select * from orders where id = '$id'";  93.    $result = $dbconn->query($sql);  94.    errortrap($result);  95.    $result->fetchinto($r);  96.    ?>  97.    <form action=admin.php method=post>  98.    <P>When changing status to "Shipped" you can include an optional tracking number that  graphics/ccc.gifis sent to the customer by email.  99.    <table border=1 cellpadding=5 cellspacing=0> 100.    <tr><td>Order ID</td><td><?=$r["id"]?></td></tr> 101.    <tr><td>Status (current status is <b><?=$r["status"]?></b>)</td> 102.      <td> 103.      <select name="status"> 104.        <option value="open">Open</option> 105.        <option value="shipped">Shipped</option> 106.        <option value="backorder">Backorder</option> 107.        <option value="hold">Hold</option> 108.      </select> 109.      </td></tr> 110.    <tr><td>Tracking Number</td><td><input type="text" name="tracking"  graphics/ccc.gifvalue="<?=$r["tracking"]?>"></td></tr> 111.    <input type=hidden name="id" value="<?=$r["id"]?>"> 112.    <input type=hidden name="customer" value="<?=$r["customer"]?>"> 113.    <tr><td colspan=2><input type="submit" name="update" value="Update Order!"></td></tr> 114.    </table> 115.    </form> 116.    <? 117.  } //end update_order 118. 119.  function update_order_process($HTTP_POST_VARS) { 120.    global $dbconn; 121.    $sql = "update orders set status= '" . $HTTP_POST_VARS["status"] . "',  graphics/ccc.giftracking_number='" . $HTTP_POST_VARS["tracking"] ."' where id='" . $HTTP_POST_VARS["id"] . graphics/ccc.gif "'"; 122.    $result = $dbconn->query($sql); 123.    errortrap($result); 124.    $message = "Your order from " .  COMPANY_NAME . " has been processed. It's current  graphics/ccc.gifstatus is:\n"; 125.    $message .= "Status: " . $HTTP_POST_VARS["status"] . "\n"; 126.    if($HTTP_POST_VARS["tracking"] != "") { 127.      $message .= "The tracking number for your shipment is " .  graphics/ccc.gif$HTTP_POST_VARS["tracking"] . "\n"; 128.    } 129.    $r_cust = get_customer($HTTP_POST_VARS["customer"]); 130.    $to = $r_cust["email"]; 131.    mail($to, COMPANY_NAME . " Order!", $message, "From: " . COMPANY_NAME . " <" .  graphics/ccc.gifCOMPANY_EMAIL .">"); 132.    ?> 133.    <h3>Status Changed!</h3> 134.    <p>The status has been updated and an email has been sent to the customer. 135.    <p>Click <a href="admin.php">here</a> to return to the administration page. 136.    <? 137.  } //end update_order_process 138. 139.  function get_customer($id) { 140.    global $dbconn; 141.    $sql = "select * from customers where id = '$id'"; 142.    $result = $dbconn->query($sql); 143.    errortrap($result); 144.    $result->fetchinto($row); 145.    return $row; 146.  } //end get_customer 147. 148.  function display_customer($r_cust) { 149.    ?> 150.    <h3>Customer Details</h3> 151.    <table border=1 cellpadding=5 cellspacing=0> 152.    <tr><td>Customer ID</td><td><?=$r_cust["id"]?></td></tr> 153.    <tr><td>First Name </td><td><?=$r_cust["first"]?></td></tr> 154.    <tr><td>Middle Initial </td><td><?=$r_cust["mi"]?></td></tr> 155.    <tr><td>Last Name </td><td><?=$r_cust["last"]?></td></tr> 156.    <tr><td>Address </td><td><?=$r_cust["address1"]?></td></tr> 157.    <tr><td>Address 2 </td><td><?=$r_cust["address2"]?></td></tr> 158.    <tr><td>City </td><td><?=$r_cust["city"]?></td></tr> 159.    <tr><td>State </td><td><?=$r_cust["state"]?></td></tr> 160.    <tr><td>Zip </td><td><?=$r_cust["zip"]?></td></tr> 161.    <tr><td>Country </td><td><?=$r_cust["country"]?></td></tr> 162.    <tr><td>Ship to Billing Address? </td><td><?=$r_cust["shiptobilling"]?></td></tr> 163.    <tr><td>Ship to Address </td><td><?=$r_cust["ship_address1"]?></td></tr> 164.    <tr><td>Ship to Address 2 </td><td><?=$r_cust["ship_address2"]?></td></tr> 165.    <tr><td>Ship to City </td><td><?=$r_cust["ship_city"]?></td></tr> 166.    <tr><td>Ship to State </td><td><?=$r_cust["ship_state"]?></td></tr> 167.    <tr><td>Ship to Zip </td><td><?=$r_cust["ship_zip"]?></td></tr> 168.    <tr><td>Ship to Country </td><td><?=$r_cust["ship_country"]?></td></tr> 169.    <tr><td>Ship to Phone </td><td><?=$r_cust["ship_phone"]?></td></tr> 170.    <tr><td>Email </td><td><?=$r_cust["email"]?></td></tr> 171.    </table> 172.    <? 173.  } //end display_customer 174. 175.  /***** MAIN *****/ 176.  require_once("../include/cart_inc.php"); 177.  $dbconn = connect(); 178.  head(); 179. 180.  if(isset($view)) { 181.    display_orders($view); 182.  } elseif(isset($update)) { 183.    update_order_process($HTTP_POST_VARS); 184.  } elseif(isset($display)) { 185.    switch($display) { 186.      case("orderdetails"): 187.        display_order_details($id); 188.        break; 189.      case("customer"): 190.        $r_cust = get_customer($id); 191.        display_customer($r_cust); 192.        break; 193.      case("update"): 194.        update_order_status($id); 195.        break; 196.      default; 197.        break; 198.    } //end switch 199.  } else { 200.    display_orders("all"); 201.  } 202.  ?> 

Script 5-5. admin.php Line-by-Line Explanation

LINE

DESCRIPTION

2-47

Define a function, display_orders(), that displays orders based on the mode selected. The modes are:

  • All (every order regardless of state)

  • Open

  • Shipped

  • Backorder

  • Hold

49-88

Define a function, display_order_details(), that displays the details for a particular order. This function is called when the user clicks on an order number. The following information is displayed:

  • Items Ordered

  • Quantity of Items

  • Customer Information

90-137

Define a function, update_order_status(), that allows an administrator to change the status of an order. An email is sent to the customers notifying them of the status change.

139-146

Define a function, get_customer(), that is used to get the information for a customer and return it to the calling function for display.

148-173

Define a function, display_customer(), that displays the information returned from get_customer(). Both of these functions are helper functions used within get_order_details().

175

Begin the main program.

176

Require the cart_inc.php script so that this script can use those functions defined in cart_inc.php.

177

Establish a connection to the database.

178

Print out the beginning HTML for the page.

180-181

If the $view variable is set, then display the orders according to the $view variable for example, $view = "open".

182-183

If the $update variable is set, then process the update using the update_order_process() function.

184-198

If the $display variable is set, then switch to the proper function based on the contents of $display.

199-201

If nothing else has been set, then display all the orders.

202

End the PHP for the page.

checkout.php

checkout.php is used to gather the customer's details and send all of the information to the credit card authorization service. In this case, it sends the information directly to finishorder.php. Normally, you would submit this page to an authorization service and the authorization service would redirect to finishorder.php. Figure 5-4 displays the checkout screen.

Script 5-6 checkout.php

[View full width]

   1. <?   2. require_once("include/cart_inc.php");   3. session_start();   4. head();   5. $dbconn = connect();   6. $response = "1";   7. //$response = "2"; //Declined Credit Card   8. //$response = "3"; //General Error   9.  10. if(sizeof($items) == 0) {  11.   ?>  12.   <h3>There are no items in your cart! Click your browser's Back button and add some  graphics/ccc.gifitems to your cart.</h3>  13.   <?  14. } else {  15. ?>  16. <h2>Here are the items that you are ordering:</h2>  17. <?  18. $status = "checkout";  19. display_cart($items);  20. ?>  21. <p>Please fill in the following information to proceed.<p>  22.   <FORM METHOD=POST ACTION="<?=CREDIT_AUTH_URL?>">  23.     <INPUT TYPE=HIDDEN NAME="Amount" VALUE="<?=$total?>">  24.     <INPUT TYPE=HIDDEN NAME="x_Description" VALUE="Order From <?=COMPANY_NAME?>">  25.     <INPUT TYPE=HIDDEN NAME="x_Invoice_Num" VALUE="<?=time()?>">  26.   <INPUT TYPE=HIDDEN NAME="x_response_code" VALUE="<?=$response?>">  27.   <?cart2form($items);?>  28.   <table border="1" cellspacing="1" cellpadding="5">  29.     <tr>  30.       <td colspan="2" ><b>BILLING ADDRESS</b>:</td>  31.     </tr>  32.     <tr>  33.       <td>Credit Card Number<span >*</span></td>  34.       <td>  35.         <input type="text" name="x_card_num">  36.       </td>  37.     </tr>  38.     <tr>  39.       <td>Expiration Date<span >* <br>  40.         (MMYY - for example 0402 for April 2002)</span></td>  41.       <td>  42.         <input type="text" name="x_exp_date" maxlength="4" size="4">  43.       </td>  44.     </tr>  45.     <tr>  46.       <td>First Name<span >*</span></td>  47.       <td>  48.         <input type="text" name="x_first_name">  49.       </td>  50.     </tr>  51.     <tr>  52.       <td>Middle Initial</td>  53.       <td>  54.         <input type="text" name="x_mi">  55.       </td>  56.     </tr>  57.     <tr>  58.       <td>Last Name<span >*</span></td>  59.       <td>  60.         <input type="text" name="x_last_name">  61.       </td>  62.     </tr>  63.     <tr>  64.       <td>Address Line 1:<span >*</span></td>  65.       <td>  66.         <input type="text" name="x_address">  67.       </td>  68.     </tr>  69.     <tr>  70.       <td>Address Line 2:</td>  71.       <td>  72.         <input type="text" name="x_address_2">  73.       </td>  74.     </tr>  75.     <tr>  76.       <td>City<span >*</span></td>  77.       <td>  78.         <input type="text" name="x_city">  79.       </td>  80.     </tr>  81.     <tr>  82.       <td>State (two letter abbreviation)<span >*</span></td>  83.       <td>  84.         <input type="text" name="x_state" size="2" maxlength="2">  85.       </td>  86.     </tr>  87.     <tr>  88.       <td>Zip/Postal Code<span >*</span></td>  89.       <td>  90.         <input type="text" name="x_zip" size="10" maxlength="10">  91.       </td>  92.     </tr>  93.     <tr>  94.       <td>Country<span >*</span></td>  95.       <td>  96.         <select name=x_country>  97.           <option> Canada  98.           <option> United Kingdom  99.           <option selected> United States 100.         </select> 101.       </td> 102.     </tr> 103.     <tr> 104.       <td>Daytime Phone Number</td> 105.       <td> 106.         <input type="text" name="x_phone"> 107.       </td> 108.     </tr> 109.     <tr> 110.       <td>Email<span >*</span></td> 111.       <td> 112.         <input type="text" name="x_email"> 113.       </td> 114.     </tr> 115.     <tr> 116.       <td>Shipping Address Is The Same As Billing Address: </td> 117.       <td> 118.         <input type="checkbox" name="shiptobilling" value="true"> 119.         <br> 120.         <font size="-2"> (Check To Ship To Your Billing Address)</font></td> 121.     </tr> 122.     <tr> 123.       <td colspan="2" > 124.         <p><b>SHIPPING ADDRESS </b><br> 125.           (Fill this out if your shipping address is different from your billing 126.           address):</p> 127.       </td> 128.     </tr> 129.     <tr> 130.       <td>Address Line 1:</td> 131.       <td> 132.         <input type="text" name="x_ship_to_address"> 133.       </td> 134.     </tr> 135.     <tr> 136.       <td>Address Line 2:</td> 137.       <td> 138.         <input type="text" name="x_ship_to_address2"> 139.       </td> 140.     </tr> 141.     <tr> 142.       <td>City</td> 143.       <td> 144.         <input type="text" name="x_ship_to_city"> 145.       </td> 146.     </tr> 147.     <tr> 148.       <td>State (two letter abbreviation)</td> 149.       <td> 150.         <input type="text" name="x_ship_to_state" size="2" maxlength="2"> 151.       </td> 152.     </tr> 153.     <tr> 154.       <td>Zip</td> 155.       <td> 156.         <input type="text" name="x_ship_to_zip" size="10" maxlength="10"> 157.       </td> 158.     </tr> 159.     <tr> 160.       <td>Country</td> 161.       <td> 162.         <select name=x_ship_to_country> 163.           <option> Canada 164.           <option> United Kingdom 165.           <option selected> United States 166.         </select> 167.       </td> 168.     </tr> 169.   </table> 170.   <p> 171.     <INPUT TYPE=SUBMIT VALUE="Submit Order"> 172.  </p> 173.</FORM> 174.<? 175.session_unset(); 176.session_destroy(); 177.} 178.?> 
Figure 5-4. checkout.php

graphics/05fig04.jpg

Script 5-6. checkout.php Line-by-Line Explanation

LINE

DESCRIPTION

2

Require cart_inc.php (we need the information contained in the define statements).

3

Start the session. We'll be using information from the $items session variable.

4

Print out the beginning HTML for the page.

5

Establish a connection to the database.

6-8

Normally, these are sent by the authorization service. Uncomment one of these to see the results in the finishorder.php script.

10-14

Check to see if there is anything in the cart. If there is not, then there is no need to present this page.

15-20

Print out a short table displaying the items that have been ordered. Set the $status variable to $checkout.

21-173

Display the form to the user.

174-176

Unset the session variables and destroy the session.

177

End the if statement started on line 10.

178

End the PHP for the page.

finishorder.php

finishorder.php is used to place the authorized order into the database. If the order is not authorized by the server (defined by a response code sent by the authorization service), then a message is displayed to the users notifying them of a problem.

If the order goes through, the order, customer, and order_details tables are updated with the new order information and a confirmation email is sent to the customer.

Script 5-7 finishorder.php

[View full width]

  1.  <?  2.  require_once("include/cart_inc.php");  3.  head();  4.  $dbconn = connect();  5.  6.  switch($x_response_code) {  7.    case("1"):  8.      if(!isset($shiptobilling)) {  9.        $shiptobilling = "false"; 10.      } 11.      $id = $dbconn->nextID('customers',true); 12.      $sql = "insert into customers values ('$id', '$x_first_name', '$x_mi',  graphics/ccc.gif'$x_last_name', '$x_address', '$x_address_2', '$x_city', '$x_state', '$x_zip',  graphics/ccc.gif'$x_country', '$shiptobilling', '$x_ship_to_address', '$x_ship_to_address2',  graphics/ccc.gif'$x_ship_to_city', '$x_ship_to_state', '$x_ship_to_zip', '$x_ship_to_country', '$x_phone', graphics/ccc.gif '$x_email')"; 13.      $result = $dbconn->query($sql); 14.      errortrap($result); 15.      $id2 = $dbconn->nextID('orders',true); 16.      $sql = "insert into orders values ('$id2', '$id', 'open', NULL)"; 17.      $result = $dbconn->query($sql); 18.      errortrap($result); 19.      foreach($cart as $code => $qty) { 20.        $id3 = $dbconn->nextID('order_details',true); 21.        $sql = "insert into order_details values ('$id3', '$id2', '$code', '$qty')"; 22.        $result = $dbconn->query($sql); 23.        errortrap($result); 24.        $sql2 = "update inventory set qty = qty-'$qty' where id = '$code'"; 25.        $result2 = $dbconn->query($sql2); 26.        errortrap($result2); 27.      } 28.      $mail = "Thank you for your order from " . COMPANY_NAME . "!\n"; 29.      $mail .= "We have received your order and we will notify you when the order ships."; 30.      mail($x_email, "Your order from " . COMPANY_NAME, $mail, "From: " . COMPANY_NAME .  graphics/ccc.gif" <" . COMPANY_EMAIL .">"); 31.      ?> 32.      <h2>Thank You!</h2> 33.      <p>Your order has been accepted. You should receive an email receipt in your email  graphics/ccc.gifaddress in a few minutes. 34.      <h3>DO NOT RELOAD THIS PAGE OR YOU MAY BE DOUBLE-BILLED FOR YOUR ORDER</h3> 35.      <? 36.      break; 37.    case("2"): 38.      ?> 39.      <h3>Your Credit Card Was Declined</h3> 40.      <p>The reason given was: <?=$x_response_reason_text?> 41.      <? 42.      break; 43.    case("3"): 44.      ?> 45.      <h3>There Was An Error Processing Your Request</h3> 46.      <p>The reason given was: <?=$x_response_reason_text?> 47.      <? 48.      break; 49.    default: 50.      ?> 51.      <h3>There Was An Error Processing Your Request</h3> 52.      <? 53.    break; 54.  } //end switch 55.  ?> 56.  <hr> 57.  </body> 58.  </html> 

Script 5-7. finishorder.php Line-by-Line Explanation

LINE

DESCRIPTION

2

Require cart_inc.php so you can use some of the functions that it contains.

3

Print out the beginning HTML for the page.

4

Establish a connection to the database.

6

Switch on the response code.

7-36

If the response code was "1", then the authorization was successful. Insert the customer and order information into the database and send a confirmation email to the customer.

37-42

If the response code was "2", then the credit card was denied. Display a message informing the user.

43-48

If the response code was "3", then there was an unspecified error. Notify the user.

49-54

If the response code was anything else, then assume a general unspecified error occurred and display a message to the user.

55

End the PHP for the page.

57-58

Close out the HTML for the page.


   
Top


Advanced PHP for Web Professionals
Advanced PHP for Web Professionals
ISBN: 0130085391
EAN: 2147483647
Year: 2005
Pages: 92

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net