Examples


The coding for these two implementations is similar to what you studied in previous chapters. The following are statement-by-statement explanations.

On the CD You will find the code for the two shopping cart applications on the CD-ROM in the folder named chapter14code. This folder contains a subfolder named images with image files for several origami models.

The PHP and MySQL Implementation

The opendbo.php file is included (using the require function) in all the scripts to establish the connection to the database. The calculated $link value and the $DBname value will be used in the script that requires opendbo.php and are declared as global variables. The script is shown in Table 14.1.

Table 14.1: PHP Script to Establish Connection to Database

<?php

Start PHP

global $DBname, $link;

Make these two global

$host="localhost";

Set $host

$user="curley";

You will need to change this

$password="12345";

You will need to change this

$DBname="orders";

You might need to change this

$link=mysql_connect($host,$user, $password);

Establish the connectiono

mysql_select_db($DBname,$link);

Select the database

?>

End PHP

For the PHP/MySQL system, define the tables using a script: createordertables as shown in Table 14.2.

Table 14.2: PHP Script for Creating the Tables for the Shopping Cart

<?php Start PHP function createtable($tname,$fields) {

Function for creating tables

global $DBname, $link;

Use global values

$query="CREATE TABLE ".$tname." (".$fields.")";

Defines the query using the parameter values

if (mysql_db_query($DBname,$query, $link)) {

Execute the MySQL operation. Check if it succeeded

print ("The table, $tname, was created successfully.<br>\n");

Print success message

}

Close out true clause

else {

Start else clause

print ("The table, $tname, was not created. <br>\n");

Print out not a success (for example, if the table was already created)

}

End else clause

}

End definition of function

?>

Close PHP

<html><head><title>Creating order project tables </title></head>

Normal HTML

<body>

HTML

<?php

Start PHP

require("opendbo.php");

Include the connecting script

$tname = "customers";

Set name of table, first to be defined

$fields="id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, fname char(30), lname char(30), billing TEXT, emailaddress char(50), pass char(30)";

Set definition of fields

createtable($tname, $fields);

Call function to create the customers table

$tname="orders";

Set name of table

$fields="id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, customer_id INT UNSIGNED NOT NULL, o_date DATE, status ENUM('open','set','billed', 'shipped'), total FLOAT(2)";

Set definition of fields

createtable($tname,$fields);

Call function to create orders table

$tname="catalog";

Set name of table

$fields="id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, p_name CHAR(30), picture CHAR(50), cost FLOAT(2)";

Set definition of fields

createtable($tname,$fields);

Call function to create orders table

$tname="ordereditems";

Set name of table

$fields="order_id INT UNSIGNED NOT NULL, p_id INT UNSIGNED NOT NULL, quantity INT NOT NULL";

Set definition of fields

createtable($tname,$fields);

Call function to create orders table

mysql_close($link);

Close link

?>

End PHP

</body>

HTML

</html>

HTML

The inputproducts.php script, shown in Table 14.3, lets authorized staff add a product to the catalog. This script is a form handler and a display of the form.

The previous script created a new database record containing a field with the address of a product image file. Table 14.4 shows the code for uploading an image file to the server, fileupload.php. See Chapter 12, Files, for more explanation and to the CD-ROM folder for Chapter 12 for the code for fileupload.php.

Table 14.3: PHP Script to Add a New Product to the Catalog Table

<html><head><title>Adding products to catalog table db</title></head>

HTML

<body>

HTML

<?php

Start PHP

require("opendbo.php");

Include connecting script

$tname = "catalog";

Set table name

// need sign in procedure

Comment indicating a place to improve this process

if (@($submitted)) {

Is this the form handler

  • $p_name = trim($p_name);

  1. Trim the inputted product name

$picture= trim($picture);

Trim the inputted name of the image file

$pattern="(http://)?([[:alnum:] \.,-_?/&=])\.((gif)|(jpg))$";

Prepare a regular expression pattern to check if this is a good file address including being an appropriate file extension for images

if (!eregi($pattern,$picture)){

Perform the check

print ("Please submit a valid address for a picture.<br>");

Print a message indicating the need to submit a valid image file address

print ("Use the BACK function on your browser to return to the form.");

Print instructions

}

Close clause for bad picture address

else {

Else clause

$picture = AddSlashes($picture); // should check for valid address

Add escaping for slashes in the file name

// should check $cost to be valid number

Possible improvement

$query = "INSERT INTO $tname values ('0','".$p_name."', '".$picture."', ".$cost.")";

Create insert query

$result = mysql_db_query($DBname, $query, $link);

Perform insert query

if ($result) {

Check if good result

print("The product was successfully added.<br>\n");

Print out message

}

End clause

else {

Start else clause

print ("The product was NOT successfully added. <br>\n");

Print out message for no success

}

End clause

$submitted = FALSE;

Reset to allow new submission

mysql_close($link);

Close link

print ("<a href=\"inputproducts. php\">Submit another product. </a><br>");

Display link to return to script again.

} //ends if good URL

Ends if clause for good picture file address

} //ends if submitted

Ends if handler

else {

Start else for displaying form

print ("<h1>Add a product to the catalog <br>\n </h1> ");

Print heading

print ("<form action=\"inputproducts.php\" method=post>\n");

Print form tag

print ("Name of product <input type=text name=\"p_name\" size=30><br>\n");

Print input tag for product name

print ("File name of picture <input type=text name=\"picture\" size=50><br>\n");

Print input tag for picture file address

print ("Cost of product <input type=text name=\"cost\" size=6><br>\n");

Print input tag for cost

print ("<input type=hidden name=\"submitted\" value=\"True\"><br>\n");

Print input tag for submitted flag

print ("<input type=submit name=\"submit\" value=\"Submit product!\"><br>\n");

Print button tag

print ("</form><br>\n");

Print end of form

}

Close the else clause

?>

End PHP

</body></html>

HTML

Table 14.4: PHP Script for Uploading Image File to Illustrate a Product

<html><head><title>File upload test </title></head><body>

HTML

<?php

Start PHP

if (@$file) {

Check if this is to handle the form (previous examples used a special form input value named

submitted)

print ("uploading file named $file_name <br>");

Print message letting the person know what is going on

print ("File size is $file_size <br>");

Print message on file size

$abspath = $PATH_TRANSLATED;

Set the variable to be the path to the current script

$stub=ereg_replace("\\fileupload. php","\\",$abspath);

Modify the variable to take out the name of the current script

$fullname = $stub . $file_name;

Add in the filename. This is the line you might need to alter for your application

print ("fullname is: $fullname.<br>");

Debugging message, letting user know where the file was placed

$size=GetImageSize($file);

Use PHP command to extract information on file. This only makes sense for image files

print ("Dimensions are: ".$size[0]." by ".$size[1]." pixels. <br>");

Print out file information

$area = $size[0]*$size[1];

Compute area

print ("Area is $area pixels.<br>");

Print out area

if (copy($file,$fullname)) {

This contains the critical step: copying the file to the proper place. Check if successful…

print ("file successfully uploaded. <br>");}

Print out message

else { print (“file could not be copied.”); }

Else clause: problem in copying file

unlink($file);

End connection to the file in temporary storage

}

Close clause that this was handler

print ("<br>upload a file to the server<br>\n");

Print out heading

?>

End PHP

<form action='fileupload.php' method=POST ENCTYPE="multipart/ form-data">

Form tag. The ENCTYPE is required for forms that have a file as one of the inputs

File <input type=file name="file"><br>

Input tag for file. This will generate a Browse button

<input type=submit name="submit" value="upload file">

Input tag for Submit button

</form>

End form

</body>

End body

</html>

End HTML

Now it is on to implementing ordering products. The orderproduct.php script is the first of four scripts that accomplishes the task for accepting and recording an order. An order is represented in the database by one record in the orders table, and one or more entries in the ordereditems table. The orderproduct script presents the products as a table. Each row of the table holds a product name and a product picture. The name is a hyperlink with the href attribute of the <a> tag set to makeorder.php followed by a question mark and the product ID. The orderproduct script, shown in Table 14.5, uses the currentcustomer cookie, if it is defined, to greet a returning customer by name.

Table 14.5: Initial PHP Script to Display Products to Customer

<html><head><title>Presenting products</title></head><body>

HTML start

<h1>Origami model store </h1><p>

HTML heading

<?php

Start PHP

require ("opendbo.php");

Include connecting script

if (@$currentcustomer) {

If current customer is defined via a cookie (this will be the ID)

print("currentcustomer id is: $currentcustomer<br>");

Debugging message

$query="SELECT fname FROM customers where id=$currentcustomer";

Define query to find customer’s name

$result=mysql_db_query($DBname,$query, $link);

Invoke query

$Num_past = mysql_num_rows($result);

Compute number returned

  • if ($Num_past!=0) {

  1. If the number isn’t zero

$fname=mysql_result($result,0, 'fname');

Take the first one (there should only be one)

print("Welcome back, $fname!<br>");

Print customized welcome message

}

Close if customer found

}

Close if cookie defined

?>

End PHP

Select product:

HTML

<table>

Start table

<?php

Start PHP

$query="Select * from catalog";

Define query

$result=mysql_db_query($DBname, $query, $link);

Invoke query to get all the products

while ($row=mysql_fetch_array($result)) {

While loop to iterate through the products

print ("<tr><td><a href= makeorder.php");

Start of printing to make the table item be an <a> tag with a call to makeorder.php

print ("?p_td" width="51%" align="left">

…with a query string carrying as

print($row['id']);

…the value of the id field of the record

print(">");

Close <a…> tag

print($row['p_name']);

Print out the name of the product

print("</a></td>");

Print out </a> tag and close table datum element

print("<td><img src=\"");

Print out next table datum: start of img tag

$picture=$row['picture'];

Store the value of the picture field of the record in a variable

print("../images/$picture");

Continue with img tag: the src value will be in the images folder, a folder parallel (subfolder of parent folder) of this script

print("\"></td></tr>");

Print closing table datum and table row tags

}

Close of while loop

print ("</table>");

Print </table> tag to end the table

mysql_close($link);

Close link to database

?>

End PHP

</body></html>

Closing HTML

The orderproduct script invokes the makeorder script, shown in Table 14.6, with a query string holding the ID of the product that the customer has clicked. The customer is given a chance to enter the quantity of the product.

Table 14.6: Present Individual Product for Customer to Enter Quantity

<html><head><title>Presenting products</title></head><body>

Starting HTML

<?php

Start PHP

require("opendbo.php");

Including connecting to database

?>

End PHP

<h1>Indicate quantity and confirm order </h1>

HTML header

<p>

Paragraph

<?

Start PHP

$query="Select * from catalog where id=$p_id";

Define query to get the record in the database corresponding to the $p_id value from the query string sent over by the call from orderproducts

$result=mysql_db_query($DBname,$query, $link);

Invoke query

$p_name=mysql_result($result,0,"p_name");

Define product name variable

$picture=mysql_result($result,0, "picture");

Define picture file name variable

$cost=mysql_result($result,0,"cost");

Define cost variable

print ("<center><img src=\"../images/$picture\">");

Print out tags to display picture

print("<br>");

Print line break

print("$p_name");

Print out product name

?>

End PHP

<form action=shoppingcart.php method=get>

HTML for form: note that this does not require any PHP

Quantity <input type=text size=3 name="quantity">

Field for quantity

<input type=submit value="Submit quantity" >

Submit button

<input type=hidden name=productid value='

Start of HTML to define a hidden variable to carry along the productid

<? print($p_id);

Restart PHP to output the $p_id value

?>

End PHP

'>

Need this quotation mark after $p_id value

</form></body></html>

Closing HTML

The makeorder script calls the shoppingcart script, shown in Table 14.7, which makes use of the cart session variable. The latest product ordered with the quantity is added to cart as a key/value pair. The total contents of the shopping cart—that is, everything ordered so far—is displayed. The customer is given the option of clicking on either of two links: one to continue shopping, and the other to check out.

Table 14.7: PHP Script to Display Current Shopping Cart

<?php

Start PHP

if (!session_is_registered(“cart”)) {

Check if cart is not yet registered as a session variable

$cart = array();

Initialize $cart to be an empty array

session_register("cart");

Register “cart” as a session variable

}

End the clause to initialize the cart

?>

Close PHP

<html><head><title>Shopping Cart</title>

HTML tags

<?

Start PHP

require("displaycartfunction.php");

Include the file holding the function to display the cart

?>

Close PHP

</head>

HTML tag

<body>

HTML body

<?php

Start PHP

require("opendbo.php");

Make connection to database

  1. ?>

  1. Close PHP

<h1>Shopping cart</h1>

HTML heading

<p>

Paragraph

<?

Start PHP

if (@$productid){

If a $productid is defined

$cart[$productid] = $quantity;

Set the value in the associative array $cart for this product ID to be the $quantity value

}

displaycart();

Call the displaycart function

?>

Close PHP

<hr>

Horizontal rule

<a href="submitorder.php"> Checkout (submit order)! </a>&nbsp; &nbsp;

Link to complete order by going to submitorder script

<a href="orderproduct.php"> More shopping! </a>

Link to more shopping by going to orderproduct

</body></html>

Closing HTML

The shoppingcart.php script and the submitorders.php script each have calls to the require function to include the displaycartfunction.php shown in Table 14.8.

Table 14.8: Script to Display the Contents of the Shopping Cart

<?php

Start PHP

//assumes that opendbo called, and session started when call is made.

Comment? on context of call

function displaycart() {

Function header

global $cart, $DBname, $link, $totalprice;

Function will use the global values set outside of the function

print ("<table>");

Print table tag

print ("<tr><td> Product ID </td><td> Product Name </td><td> Quantity </td><td> Total cost </td></tr>");

Print table tags for column headings

$items = 0;

Initialize $items. This will hold the number of products ordered

$totalprice = 0.00;

Initialize $totalprice. This will hold the dollar total

foreach (@$cart as $pid => $qty) {

A loop to iterate through all the key/value pairs in the $cart array

$items += $qty;

Increment the number of items by the $qty value. This is equivalent to $items=$items + $qty;

$query="Select * from catalog where id=$pid";

Define the query to get the record for the product with ID equal to $pid

$result = mysql_db_query($DBname, $query, $link);

Invoke the query

$item_price = mysql_result($result,0, "cost");

Set a variable with the item’s cost

$item_name = mysql_result($result,0, "p_name");

Set a variable with the item’s name

$item_total_price = $item_price * $qty;

Calculate the cost for the number of items ordered

$totalprice += $item_total_price;

Add this value to the variable holding the total

$item_total_pricef = number_format($item_total_price,2);

Prepare a formatted string with the total (two decimal places)

print ("<tr><td> $pid </td><td> $item_name </td><td> $qty </td><td>&nbsp;$item_total_pricef </td></td> ");

Print out the results

}

End the foreach iterating over each item in the cast

$totalpricef = "$" . number_format($totalprice,2);

Prepare a formatted string for the over all total

print("<tr><td> TOTALS </td><td></td><td> $items items</td><td>$totalpricef </td></tr></table>");

Print out the totals

}

End the definition of the function

?>

End PHP

The shoppingcart.php script contains a link to the submitorders.php script, shown in Table 14.9, for immediate checkout or the ordersproduct script for more shopping. The submitorders.php script presents a form and handles the form An If test determines which of the two to do.

Table 14.9: PHP Script to Display and Handle Form for Customer Data

<?php

Start PHP

session_start();

Re-start the session

require("opendbo.php");

Include the connection to the database

require("displaycartfunction.php");

Include the displaycartfunction code

$today = Date("Y-m-d");

Set $today to be the date in Year-month-day format

if (!@$submitconfirm) {

If form not yet submitted

print ("Please give information for ordering or confirm information present.<br>");

Print out instructions

print ("<form action=\"$PHP_SELF\" method=post><br>");

Print out form tag. Notice the use of $PHP_SELF to indicate this script

$ofname=""; $olname=""; $obilling=""; $oemail="";

Initialize several variables to empty strings. They will be used as is if there is not a current customer cookie

if (@$currentcustomer)

Check if there is a currentcustomer cookie (which would hold a customer ID)

{$query="SELECT * from customers where id=$currentcustomer";

Define a query to get that customer’s record

$result=mysql_db_query($DBname, $query,$link);

Invoke the query

$Num_past = mysql_num_rows($result);

Find out the number of records

if ($Num_past>0) {

If there is at least one record (there would be zero or 1 since IDs are unique)

$obilling=mysql_result($result,0, "billing");

Get the billing information

$olname = mysql_result($result,0, "lname");

Get the customer name

$oemail=mysql_result($result,0, "emailaddress");

Get the mail information

print ("<input type=hidden name=oldcustomer value=TRUE>");

Print out hidden input tag holding a variable that flags that the form has information from a current customer

print("<br>INFO OKAY <input type=\"radio\" name=\"choices\" value=\"OKAY\" CHECKED >");

Print out radio buttons: the information is either okay, which is the default

print ("<br>CHANGE MY INFO <input type=\"radio\" name=\"choices\" value=\"CHANGE\" >");

… radio button indicating change, which the customer clicks if he or she puts in new information

print ("<br>NEW CUSTOMER <input type=\"radio\" name=\"choices\" value=\"NC\"><br>");

Radio button for a new customer

}

Ends clause for customer in database

}

Ends clause for existence of cookie

print ("First Name <input type=text name='fname' value='".$ofname."'><br>");

Print out input tag. There might or might not be a displayed value

print ("Last Name <input type=text name='lname' value='".$olname."'><br>");

Print out input tag as above

print ("Billing information <input type=text name='billing' value='".$obilling."'><br>");

Print out input tag as above

print ("E mail address <input type=text name='email' value='".$oemail. "'><br>");

Print out input tag as above

print ("<input type=hidden name='submitconfirm' value=TRUE>");

Print out a hidden input tag to flag that form has been submitted

print ("<input type=submit name='submit' value='SUBMIT/CONFIRM INFORMATION'>");

Print out the Submit button

print ("</form>");

Print out the form end tag

  • }

  1. Ends clause for displaying form

else {

Else (handle form)

if (!@$oldcustomer) {

If it was not a case of an old customer

$query="INSERT INTO customers VALUES ('0','".$fname;

Define query to add a new record

$query=$query."','".$lname."','".$billing."','".$email."','X')" ; // X for pass now

Construction of query takes two statements

$result=mysql_db_query($DBname, $query,$link); //need error handling.

Invoke query

$currentcustomer=mysql_insert_id();

The mysql_insert_id function returns returns the id of the record just inserted.

setcookie("currentcustomer",$currentcustomer); //sets permanent cookie

Set the cookie to be this new value

}

End if not old customer

else {

Start clause for it being the case of an old customer

if (@$choices=='CHANGE') {

If the customer changed information

$query="UPDATE customers set fname='".$fname ;

Create a query for changing (updating) the information

$query = $query . "', lname='".$lname."', billing='".$billing;

Continue construction of query

$query = $query . "', emailaddress='".$email ."' where id=$currentcustomer";

Continue

mysql_db_query($DBname,$query, $link);

Invoke query

}

End old customer/new information clause

else if (@$choices=='NC') {

Start clause for choice to make new customer

$query="INSERT INTO customers VALUES ('0','".$fname;

Create query

$query=$query."','".$lname."', '".$billing."','".$email."','X')" ; // X for pass now

Continue constructing query

$result=mysql_db_query($DBname, $query,$link); //need error handling.

Invoke query

$currentcustomer=mysql_insert_id();

Obtain ID of record just created

$duration = 90 * 24 * 60* 60; //90 days

Time period for this cookie will be 90 days

setcookie("currentcustomer",$currentcustomer, time()+$duration); //sets long term

Set cookie with duration parameter

}

End if changed to new customer

}

End else clause for it being an old customer

print("Welcome, $fname <br>");

Print out welcome

print ("Today is $today <br>\n");

Print out date

print ("Here is your order.<hr>");

Print out heading

displaycart();

Invoke displaycart function to display the whole cart

print ("<hr> We are billing it using the following information: <br>$billing<br>");

Print out information on billing

$query = "INSERT INTO orderlist VALUES ('0', '";

Start construction of query to insert record into the orderlist table

$query = $query . $currentcustomer."', '".$today."', 'set',".$totalprice.")";

Continue construction

mysql_db_query($DBname, $query, $link);

Invoke query

$orderid=mysql_insert_id();

Obtain ID of record just created

foreach ($cart as $pid=>$qty) {

Use foreach to iterate over cart to insert insert records into the ordereditems table

$query="INSERT INTO ordereditems values ('".$orderid."','".$pid."',". $qty.")";

Create the query

mysql_db_query($DBname,$query,$link);

Invoke query

} //ends the foreach

End iteration through cart

session_unregister('cart');

Unregister the cart session variable

unset($cart); $cart

This returns any space used by

session_destroy();

Stop the session

}

Ends handling of form—the else clause on if submitconfirm

?>

Close PHP

</body></html>

Closing HTML tags

The ASP and Access Implementation

The ASP implementation bears the same relationship to the PHP implementation as prior projects. Our suggestion is to create the database with all the tables in stand-alone mode; that is, directly in Access. This means that there is no ASP file that corresponds to the createtables.php file.

The openconn.asp script shown in Table 14.10, holds the code for connecting to the database named orders.mdb located in the folder as these scripts. It is of the DSN-less type.

Table 14.10: The ASP/JavaScript Script to Connect to the Database

<%

Start ASP

Conn = Server.CreateObject("ADODB. Connection");

Create connection object

Conn.Mode = 3 ;

Set mode to read/write

strConnect = "Driver={Microsoft Access Driver (*.mdb)};" + "DBQ=" + Server.MapPath("orders.mdb") ;

Define the connection string to point to the appropriate driver and database

Conn.Open (strConnect, "admin", "") ;

Make the connection, using a general user and no password

%>

Close ASP

The inputproduct.asp file, shown in Table 14.11, is used to input products.

Table 14.11: The ASP/JavaScript Script for Inputting a New Product

<%@ Language=JavaScript %>

Set language

<html><head><title> Adding products to catalog table </title></head><body>

HTML

<!— #include file="openconn.asp" —>

Include file to establish connection

<%

Start ASP

var submitted=String(Request.Form ("submitted"));

Extract from form input the variable that flags if this is form or handler

if (submitted !="undefined") {

Check submitted

var pname=String(Request. Form("pname"));

Extract pname from form input

var picture=String(Request. Form("picture"));

Extract picture file name from form input

var cost=Request.Form("cost");

Extract cost

if (picture=="") {

Check if picture not given

Response.Write("Please submit a valid address for a picture.<br>");

Error message

Response.Write("Use the browser BACK to return to the form.<br>");

Instructions to return to form

}

End clause

else {

Else

queryf = "(p_name, picture, cost)";

Part of setting up insert query

queryv = " VALUES ('" + pname + "','" + picture +"', " + cost + ")";

Part of setting up insert query

query="INSERT INTO catalog " + queryf + querytv;

Part of setting up insert query

if (Conn.Execute(query))

Execute query and do IF test

{Response.Write("<br>Product was successfully entered. <br>");}

Write out success

else {Response.Write("Product was NOT entered.<br>");

Write out failure

}

End clause

Conn.Close();

End connection

Response.Write("<a href=\"inputproducts.asp\">Another product? </a><br>");

Display a link to go to submit another product

}

Ends if good picture

} // ends if submitted

Ends if handling form

else {

Else: present form

%>

Stop ASP

<h1>Add product to the catalog<br></h1>

HTML heading

<form action="inputproducts.asp" method="POST"><br>

Form tag

Product name <input type=text name="pname" size=50><br>

Input field for product name

Picture file <input type=text name="picture" size=50><br>

Input field for picture file name

Cost <input type=text name="cost" size=6><br>

Input field for cost

<input type=hidden name="submitted" value="True"><br>

Input field for submitted, which works as a flag indicating form is to be handled

<input type=submit name="submit" value="Enter product!"><br>

Submit button

</form>

Form close tag

<%

Restart ASP

}

Close else clause for submitting form

%>

End ASP

</body></html>

HTML closing tags

Now we get to the set of scripts for ordering products. The first one is orderproduct.asp, shown in Table 14.12.

Table 14.12: The ASP/JavaScript Script for Ordering Products

<%@ Language=JavaScript %>

Set language

<!— #include file="openconn.asp" —>

Include file for connecting to the database

<html><head><title>Presenting Products </title><head><body>

HTML starting tags

<h1>Origami model store </h1>

Heading

<%

Start ASP

currentcustomer = String(Request. Cookies("currentcustomer"));

Extract cookie holding currentcustomer

if (currentcustomer!="") {

If cookie was set

query="SELECT fname FROM customers WHERE customer_td" width="44%" align="left">

Creating query to get that customer record

result=Server.CreateObject("ADODB. RecordSet");

Create recordset object

result.Open(query,Conn);

Invoke query

fname=String(result.fields.item("fname"));

Extract the fname field from that record

Response.Write("Welcome back, "+fname+"<br>");

Display customized greeting

}

End if cookie set

%>

End ASP

Select Product:

Instructions

<table>

HTML table tag

<%

Start ASP

query="SELECT * from catalog";

Define query

rs=Server.CreateObject("ADODB. RecordSet");

Create recordset object

rs.Open(query,Conn);

Invoke query

while (!rs.EOF) {

While loop to iterate through all the items in the catalog

Response.Write("<tr><td><a href=makeorder.asp?p_td" width="44%" align="left">

Start to display, as first item in row of table, an a tag, with the href value for the link makeorder.asp plus the start of a query string

Response.Write(rs.fields.item("p_id"));

The rest of the query string is the product identifier

Response.Write(">");

Close up the <a> tag

Response.Write(rs.fields.item("p_name"));

Write out the product name as the visible part of the link

Response.Write("</a></td><td><img src="/books/2/886/1/html/2/);

Output the </a> tag along with more table tags and the start of an img tag

Response.Write(rs.fields.item("picture"));

Output the picture file

Response.Write("></td></tr>");

Output the table tags closing up the row

rs.move(1);

Advance in the record set

}

Close up the while loop

Response.Write("</table>");

Output the closing table tag

Conn.close();

Close the connection to the database

%>

End ASP

</body></html>

HTML tags

The orderproduct script contains tags with links to the makeorder.asp script. A query string holds the product ID value for the link the customer clicks. The makeorder script, shown in Table 14.13, allows the customer to indicate the quantity.

Table 14.13: The ASP/JavaScript Script for Specifying the Quantity

<%@ Language=JavaScript %>

Set language

<!— #include file="openconn.asp" —>

Include code to connect to database

<!— #include file="moneyformat.asp" —>

Include code to format money

<html><head><title>Input quantity </title></head><body>

HTML tags

<h1>Indicate quantity and confirm order </h1><p>

HTML heading

<%

Start ASP

p_id = Request("p_id");

Extract the product ID from the query string

query="Select * from catalog where p_td" width="40%" align="left">

Create query for selecting that record

result=Server.CreateObject("ADODB. RecordSet");

Create a recordset object

result.Open(query, Conn);

Invoke query

p_name=String(result.fields.item("p_name"));

Extract product name

picture=String(result.fields.item("picture"));

Extract picture filename

cost=result.fields.item("cost");

Extract cost

Response.Write("<center><img src='/books/2/886/1/html/2/"+picture+"'>");

Write out HTML to display image

Response.Write("<br>");

Write out line break

Response.Write(p_name);

Write out product name

Response.Write("<i> price @ item </i> ");

Write out text

Response.Write(money(cost));

Write out cost formatted as money

%>

End ASP

<form action=shoppingcart.asp method=post>

Form field. The script indicated to handle the form is shoppingcart.asp

Quantity <input type=text size=3 name="quantity"><br>

Quantity field

<input type=submit name=submit value="Submit Quantity">

Submit button

<input type=hidden name=productid value='

The productid is passed along as an additional form value

<%

Start ASP

Response.Write(p_id);

Write out product ID

%>

End ASP

'>

Output quotation mark to follow product ID

</form>

End form

</body>

End body

</html>

End HTML

The moneyformat script, shown in Table 14.14, does not add a dollar sign, but does make sure that the amount is given with two decimal places.

Table 14.14: The ASP/JavaScript Script Holding the Function for Formatting Money

<%

Start ASP

function money( raw) {

Function definition header. The parameter is named raw

var thirdd = 0.0050000001;

Set third to be used for rounding up

var dandc = "" + ( raw + thirdd );

The dandc is set by first adding raw and thirdd as numbers and then concatenated with the empty string to produce a string

var dp = dandc.indexOf ( '.' );

Find the decimal point

var zeros;

The variables zeroes will be used later

if ( dp < 0 ) {

If there is no decimal point

dandc = dandc + '.00'; }

…concatenate two zeros to the end of dandc

else {

Else (there was a decimal point)

dandc = dandc.slice ( 0, dp + 3 );

If there are two or more decimal places, this reduces the string to extend just two places past the decimal point

zeros = 3 - ( dandc.length - dp );

Zeros will be greater than zero only if the string had less than two decimal places

for ( var i=0; i<zeros; i++ ) {

For loop: if zeros is greater than zero

dandc = dandc + '0'; }

Add zero to the end, as needed

}

End for loop

return dandc;

Return dandc

}

End function

%>

End ASP

The shoppingcart.asp, shown in Table 14.15, script displays all items bought so far and gives the customer a chance to complete the order (checkout) or return for more shopping.

Table 14.15: The ASP/JavaScript Script Displaying the Shopping Cart

<%@ Language=JavaScript %>

Set language

<!— #include file="openconn.asp" —>

Include file to make connection to database

<!— #include file="displaycartfunctions. asp" —>

Include file with function to display the cart

<html><head><title> Start or add to shopping cart </title></head><body>

HTML tags

<%

Start ASP

npid = String(Request.Form("productid"));

Extract product ID from form input

nqty = parseInt(Request.Form("quantity"));

Extract quantity from form input

Session(npid) = nqty;

Add to the session information a key/value pair, with the key being the product ID and the value being the quantity

tqty=0

Initialize variable holding total quantity of items to zero

totalcost = 0.00;

Initialize variable holding total cost to zero

displaycart();

Call displaycart function

Conn.close();

Close connection

%>

Close ASP

<br>

Line break

<a href="orderproduct.asp"> Enter new item </a>

Link for more shopping

<br>

Line break

<a href="submitorder.asp"> Complete order </a>

Link to complete order

</body></html>

Closing HTML tags

The displaycartfunctions script, shown in Table 14.16, holds the one function displaycart.

Table 14.16: The ASP/JavaScript Script Holding the displaycart Function

<!— #include file="moneyformat.asp" —>

Include the moneyformat function

<%

Start ASP

function displaycart() {

Function header

rs=Server.CreateObject("ADODB.RecordSet");

Create a recordset object

Response.Write("<hr>");

Output horizontal rule

Response.Write("<table>");

Output table tag

Response.Write("<thead>");

Output more table tags

Response.Write("<th>Name <th> Unit Cost <th> Quantity <th> Cost <TBODY>");

Table column headings

for (i=1; i<=Session.Contents. Count;i++) {

For loop to iterate through the Session.Contents

itemn = Session.Contents. key(i);

Set itemn to be a key value

query="Select p_name, cost from catalog where p_td" width="33%" align="left">

Create a query to get that record

rs.Open(query, Conn);

Invoke the query

pn=String(rs.fields.item("p_name"));

Extract the product name

pc=parseFloat(rs.fields. item("cost"));

Extract the cost and convert to a decimal number

rs.Close();

Close the recordset (it may be re-used)

pqty=parseInt(Session(itemn));

Obtain the quantity from the Session information. Convert to be an integer

tqty=tqty+pqty;

Add to the running total quantity variable

ptotal = pc*pqty;

Compute the cost

totalcost=totalcost+ptotal;

Add to the running total cost variable

Response.Write("<tr><td>" + pn + " </td>");

Output table tags plus the product name

Response.Write("<td>" + money(pc) + "</td>");

Output table tags plus the formatted (unit) cost

Response.Write("<td>" + pqty + " </td>");

Output table tags plus the quantity

Response.Write("<td>" + money(ptotal) + " </td>\n </tr>");

Output the formatted total cost for this product

}

Close loop through shopping cart

Response.Write("<tr><td> Totals </td><td></td><td>"+ tqty+"</td><td>");

Output as the last row of the table the totals

Response.Write("<b>$ " +money(totalcost));

Continue outputting last row

Response.Write("</b></td></tr></table>");

Finish up last row

}

Close function definition

%>

Close ASP

The script that actually stores the order information in the database is submitorders.asp, shown in Table 14.17. It first displays a form and requests that the customer confirm, change, or enter new customer information. The same script then handles the form information.

Table 14.17 : The ASP/JavaScript Script to Collect and Handle Customer Information

<%@ Language="JavaScript" %>

Set language

<!— #include file="openconn.asp" —>

Include connecting to database

<!— #include file="displaycartfunctions. asp" —>

Include code to display shopping cart

<%

Start ASP

dx= new Date();

Define dx as a date object holding today’s date

today = dx.getDate()+"-"+ dx.getMonth()+"-"+dx.getFullYear();

Define today as a string with formatted information from dx

var submitted=String(Request. Form("submitted"));

Extract submitted flag to check if this

if (submitted =="undefined") {

Check if handler or form. The positive if test is to display the form

Response.Write("Please confirm or give new information.<br>");

Output instructions to customer

Response.Write("<form action=\"submitorder.asp\" method=post><br>");

Output form header

ofname=""; olname=""; obilling=""; oemail="";

Initialize variables to be used in the display

currentcustomer = String(Request. Cookies("currentcustomer"));

Extract cookie value

if (currentcustomer!="") {

Check if cookie was set

query="SELECT * FROM customers WHERE customer_td" width="36%" align="left">

Define query to get this customer’s record from the database

result=Server.CreateObject("ADODB.RecordSet");

Define a recordset object

result.Open(query,Conn);

Invoke query

ofname=String(result.fields.item("fname"));

Set ofname with the value from the database

olname=String(result.fields.item("lname"));

Set olname with the value from the database

obilling=String(result.fields.item("billing"));

Set obilling with the value from the database

oemail=String(result.fields.item("emailaddress"));

Set oemail with the value from the database

Response.Write("<input type=hidden name=oldcustomer value='TRUE'>");

Write out as a hidden tag that there was information from an “old’” customer

Response.Write("<br>Okay<input type=\"radio\" name=\"choices\" value=\"OKAY\" CHECKED >");

Write out as radio button with the default, that the information was okay

Response.Write("Change<input type=\"radio\" name=\"choices\" value=\"CHANGE\" >");

Write out as radio that the information needed to change (but for the same, “old,” customer)

Response.Write("New Customer<input type=\"radio\" name=\"choices\" value=\"NC\" >");

Write out as radio button the choice that this is a new customer

}

Close if clause for cookie existing

Response.Write("<br>First Name <input type=text name='fname' value='" +ofname+ "'><br>");

Output input tag for first name. The value showing is taken from ofname. It is empty if the cookie did not exist

Response.Write("Last Name <input type=text name='lname' value='"+ olname + "'><br>");

Output input tag for last name

Response.Write("Billing <input type=text name='billing' value='"+ obilling + "'><br>");

Output input tag for billing

Response.Write("Email <input type=text name='email' value='" + oemail+ "'><br>");

Output input tag for e-mail

Response.Write("<input type=hidden name='submitted' value='TRUE'>");

Output as hidden form tag the submitted value

Response.Write("<input type=submit name='submit' value='SUBMIT/CONFIRM INFORMATION'>");

Output Submit button

Response.Write("</form>");

Output form close

}

End clause for the situation to present the form

else

Else clause: form handler

{oldcustomer=Request.Form("oldcustomer");

Extract oldcustomer value. This is the hidden value indicating if there was an “old customer”

fname=String(Request.Form('fname'));

Extract fname value

lname=String(Request.Form('lname'));

Extract lname

billing=String(Request.Form('billing'));

Extract billing

email=String(Request.Form('email'));

Extract e-mail

if (oldcustomer!='TRUE') {

If there was not an old customer

fieldsx = "(fname, lname, billing, emailaddress)";

Start to prepare query to insert a new customer record

valuesx = " ('" + fname +"','" + lname + "','" + billing + "','"+ email+ "')";

Continue with preparation of query

query="INSERT INTO customers "+ fieldsx + " VALUES " + valuesx;

Define query

Conn.Execute(query);

Execute query

query="SELECT max(customer_id) as maxid from customers";

This produces the id of the record just added to the table

rs=Server.CreateObject("ADODB. RecordSet");

Define a new recordset

rs.Open(query, Conn);

Invoke query

currentcustomer=rs.fields. item("maxid");

This is the ID of the customer whose record was just inserted (added)

}

Ends if not old customer; i.e., new customer

  • else {

  1. Else (old customer)

currentcustomer = String (Request.Cookies("currentcustomer"));

Extract the current customer ID from the form

choices = Request.Form("choices");

Extract the value of choices

if (choices=="CHANGE") {

If choices indicates a change

query="UPDATE customers set fname ='"+fname+"', lname='" +lname;

Start creation of the query to update (change) the customer information

query= query+"', billing='"+billing+"', emailaddress='"+email+"'";

Continue with query

query= query +" where customer_id ="+currentcustomer;

Complete creation of query

Conn.Execute(query);

Invoke query

}

Ends change info but same currentcustomer

else if (choices=='NC') {

Else if new customer

fieldsx = "(fname, lname, billing, emailaddress)";

Start to prepare query for insertion

valuesx = " ('" + fname +"', '" + lname + "','" + billing + "', '" + email+ "')";

Continue preparing query

query="INSERT INTO customers "+ fieldsx + " VALUES " + valuesx;

Complete query

Conn.Execute(query);

Invoke query

query="SELECT max(customer_id) as maxid from customers";

Define query to obtain the ID for the record just inserted

rs=Server.CreateObject("ADODB. RecordSet");

Define new recordset

rs.Open(query, Conn);

Invoke query

currentcustomer=rs.fields. item("maxid");

Extract value. This is the ID for the record just created

}

Ends make new currentcustomer

}

Ends old customer

Response.Write("Welcome, "+fname);

Output greeting

Response.Write("<br>Today is "+ today);

Output date

Response.Write("<br>Here is your order. <hr>");

Output message

tqty=0

Initialize variable that will hold total quantity

totalcost = 0.00;

Initialize variable that will hold total cost

displaycart();

Call displaycart

Response.Write("We are billing it using: <br>"+billing+"<br>");

Output message on billing

fieldsx="(customer_id, o_date, status, total)";

Start to prepare query for insertion into orders table

valuesx="('"+ currentcustomer+"', '"+ today+"','set',"+ totalcost+")";

Continue

query="INSERT INTO orderlist "+ fieldsx + " VALUES "+ valuesx;

Complete query

Conn.Execute(query);

Invoke query

query="SELECT max(order_id) as maxid from orderlist";

Define new query to get ID of record just added to orderlist

rs=Server.CreateObject("ADODB. RecordSet");

Define new recordset

rs.Open(query, Conn);

Invoke query

order_id=rs.fields.item("maxid");

Extract value of order_id

fieldsx="(order_id, p_id, quantity)";

Start preparation of query for insertion into ordereditems table. This same string will be part of the query for each item

for (i=1; i<=Session.Contents. Count;i++) {

For loop: for each product ordered. The iteration is over the Sessions.Contents

itemn = Session.Contents. key(i);

Extract product ID

pqty=parseInt(Session(itemn));

Extract the associated quantity and convert to be integer

valuesx = "("+order_id+","+itemn+","+pqty+")";

Continue with preparation of query

query="INSERT INTO ordereditems "+fieldsx+ "VALUES"+valuesx;

Complete definition of query

Conn.Execute(query);

Invoke query

}

Close for loop

Conn.Close();

Close connection

Session.Abandon;

Destroys all session variables; that is, the cart

}

Ends handling of form

%>

End ASP

</body></html>

Closing HTML tags




Creating Database Web Applications with PHP and ASP
Creating Database Web Applications with PHP and ASP (Charles River Media Internet & Web Design)
ISBN: 1584502649
EAN: 2147483647
Year: 2005
Pages: 125
Authors: Jeanine Meyer

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