Shopping Cart/E-Commerce Tutorial
Using Arrays & Structures
-Part 2 of 3-
By Michael Bamberger

Tutorial Index
#Section Title
1. Database Layout
2. Member Sign Up
3. *Main Shopping Cart Page
4. *Product Display - "Add to Cart"
5. Checkout - Order Processing
6. Supplemental Coding - Navigation Include

This is the MAIN part of the tutorial. This is where we set up our shopping cart and learn how to add products into it.

Section 3 - Main Shopping Cart Page

Coding a shopping cart really is not very hard at all. All you need is knowledge of arrays and structures and you're ready to go. I will first show all the scripting for this part and then describe each part of the coding in more detail.

cart.cfm - The actual shopping cart page.
<cfif IsDefined('session.shoppingcart') is "NO">
Your shopping cart is currently empty.
<cfelse>
<cfset totalItems = 0>
<cfloop from="1" to="#arrayLen(session.shoppingcart)#" index="i">
<cfset totalItems = variables.totalItems + session.shoppingcart[i].quantity>
</cfloop>
<cfif totalItems EQ 0>
Your shopping cart is currently empty.
<cfelse>

<p>
<table width="90%" align="center" border="0" cellpadding="2" cellspacing="0" style="border:2px solid #DDDDDD;">
<tr>
<td colspan="7" style="font-weight:bold;font-size:11pt;background-color:#DDDDDD">Items in Shopping Cart</td>
</tr>
<tr>
<td><b>#</b></td><td><b>Product</b></td><td><b>Size</b></td><td><b>Unit Price</b></td><td><b>Quantity</b></td><td><b>Total</b></td><td><b>Action</b></td>
</tr>
<cfoutput>
<cfloop from="1" to="#arrayLen(session.shoppingcart)#" index="i">
<cfset total[i] = session.shoppingcart[i].price * session.shoppingcart[i].quantity>
<tr style="background-color:##<cfif i MOD 2>EFEFEF<cfelse>FFFFFF</cfif>;">
<td>#i#</td>
<td>#session.shoppingcart[i].name#</td>
<td>#session.shoppingcart[i].size#</td>
<td>#DollarFormat(session.shoppingcart[i].price)#</td>
<td>#session.shoppingcart[i].quantity#</td>
<td>#DollarFormat(total[i])#</td>
<td><a href="delete_item.cfm?id=#i#">Remove Item</a></td>
</tr>
</cfloop>
</cfoutput>
<cfset totalprice = 0>
<cfloop from="1" to="#arrayLen(session.shoppingcart)#" index="i">
<cfset totalprice = variables.totalprice + total[i]>
</cfloop>
<tr style="background-color:#DDDDDD;">
<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td><b><cfoutput>#DollarFormat(variables.totalprice)#</cfoutput></b></td><td><a href="checkout.cfm"><b>Checkout</b></a></td>
</tr>
</table>
<p>
You currently have <cfoutput><strong>#variables.totalItems#</strong></cfoutput> <cfif variables.totalItems EQ 1>item<cfelse>items</cfif> in your cart.<br>
<a href="checkout.cfm"><b>Proceed to Checkout >></b></a><p>
<a href="clear_cart.cfm">Clear Shopping Cart</a>
</cfif>
</cfif>



See, it's not so bad at all. Very little coding. Now to the explanations:

<cfif IsDefined('session.shoppingcart') is "NO">
Your shopping cart is currently empty.
<cfelse>

This part simply sees if a shopping cart is defined. If it isn't, then you tell the user that their shopping cart is empty.

<cfelse>
<cfset totalItems = 0>
<cfloop from="1" to="#arrayLen(session.shoppingcart)#" index="i">
<cfset totalItems = variables.totalItems + session.shoppingcart[i].quantity>
</cfloop>
<cfif totalItems EQ 0>
Your shopping cart is currently empty.
<cfelse>

Now, we do a loop. Since we have already discovered that a shopping cart exists, we loop through to see what products we have in there. This part is from CJ's tutorial and he explains it well there. If it turns out our shopping cart exists, but the user deleted all the items, it again tells the user the shopping cart is empty.

Now, if the user has products in their cart, we show everything to them.

<cfoutput>
<cfloop from="1" to="#arrayLen(session.shoppingcart)#" index="i">
<cfset total[i] = session.shoppingcart[i].price * session.shoppingcart[i].quantity>
<tr style="background-color:##<cfif i MOD 2>EFEFEF<cfelse>FFFFFF</cfif>;">
<td>#i#</td>
<td>#session.shoppingcart[i].name#</td>
<td>#session.shoppingcart[i].size#</td>
<td>#DollarFormat(session.shoppingcart[i].price)#</td>
<td>#session.shoppingcart[i].quantity#</td>
<td>#DollarFormat(total[i])#</td>
<td><a href="delete_item.cfm?id=#i#">Remove Item</a></td>
</tr>
</cfloop>
</cfoutput>

This code comes after we format our table. We loop through our shopping cart and display all of the information. We set the price for the total for each item determined by its price and quantity (total[i]), and then display all the information. We use the "DollarFormat" function to put a dollar sign before the price and limit the decimal places to two.

<cfset totalprice = 0>
<cfloop from="1" to="#arrayLen(session.shoppingcart)#" index="i">
<cfset totalprice = variables.totalprice + total[i]>
</cfloop>
<tr style="background-color:#DDDDDD;">
<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td><b><cfoutput>#DollarFormat(variables.totalprice)#</cfoutput></b></td><td><a href="checkout.cfm"><b>Checkout</b></a></td>

Now we determine the total price of all of the items in the shopping cart to display to the user. We loop through the cart and keep adding the total[i] prices we determined in earlier coding until we reach the end of our cart. Then you see we display it again using the DollarFormat function.
The end of the coding just displays the total products that we calculated earlier.

Now, as you might have noticed, there is a link that says "Remove Item" when our products are displayed in the shopping cart. When the user clicks this, it deletes the item from the shopping cart array. Below is the coding.

delete_item.cfm - Page that removes the item from our shopping cart.
<cfset temp = arrayDeleteAt(session.shoppingcart, #URL.id#)>
<script>
self.location="cart.cfm";
</script>


Very simple. It uses the ArrayDeleteAt function to remove the item from the cart. It uses the variable passed from the product display page to know which item to remove. Then, we use a quick script to forward the user back to the cart.

You probably also notice the "Clear Cart" link. This is similar to the "Remove Item" link, but clears out the entire cart.

clear_cart.cfm - Page that clears out the entire shopping cart.
<cfscript>
ArrayClear(session.shoppingcart);
</cfscript>
<script>
self.location="cart.cfm";
</script>


As you can see, we don't delete the items, actually. We clear out the entire array that is session.shoppingcart. This is the easiest and most efficient way. We don't want to clear the entire session structure, because the user may be logged in and that would log them out. Keep that in mind with your "logout" script for your site. Just because a user logs out doesn't mean he wants to clear out his shopping cart. They may want to log in under another account.

Phew, ok, that was the hard part. And it wasn't too bad at all. If you look closely at the coding you will definitely be able to understand all of it, no matter what your level of ColdFusion knowledge. As you can see, its apparent that we set all of those structure values earlier inside our shopping cart (which is our main array). Now, you may be thinking, when is our cart defined? and, when is that information added for each product? Well, that all happens in our very next section!

Section 4 - Product Display - "Add to Cart"
Before we add the product to the shopping cart, we have to show our products to our user. This is just a basic display script that gets all of the products from the database. Of course, you can use the different columns in your products table to only show certain items.

product_display.cfm - The page that shows our products to the customer.
<cfquery name="getProds" datasource="test">
SELECT *
FROM LProducts
ORDER BY p_name ASC
</cfquery>

<table border=0 width="100%" cellpadding="2" cellspacing="0">
<tr>
<td><b>Product</b></td><td><b>Price</b></td><td><b>Quantity</b></td>
</tr>
<cfoutput query="getProds">
<form name="Add#getProds.p_id#" action="addtocart.cfm" method="post">
<tr style="background-color:##<cfif currentrow MOD 2>EFEFEF<cfelse>FFFFFF</cfif>;">
<td>#getProds.p_name#</td>
<td>#DollarFormat(getProds.p_price)#</td>
<td><input type="hidden" name="id" value="#getProds.p_id#">
<input type="hidden" name="name" value="#getProds.p_name#">
<input type="hidden" name="p" value="#getProds.p_price#">
<input type="text" name="qnt" value="1" OnKeyPress="if(((event.keyCode < 48) || (event.keyCode > 57))) event.returnValue = false;" maxlength="3"> <input type="submit" value="Add to Cart">
</td>
</tr>
</form>
</cfoutput>
</table>

This is very simple coding. We first query the database for all of our products and then sort them by name. Then, we set up a form for each product by giving each form a name that is "Add" and then the product ID number - making each form unique. We then simply output all of the information about our product we want the customer to see. You'll notice there are a few hidden values. These are used to pass variables that we need when the product is added to the shopping cart. The product name, price, and quantity are all added. Quantity is input by the user and they can change the default value of 1.

addtocart.cfm - The page that actually adds our item to the cart.
<cfif IsDefined('session.shoppingcart') is "NO">
<cfset session.shoppingcart = arrayNew(1)>
</cfif>
<cfset newitem = 0>
<cfloop from="1" to="#arrayLen(session.shoppingcart)#" index="i">
<cfif session.shoppingcart[i].productid EQ #form.id#>
<cfset session.shoppingcart[i].quantity = session.shoppingcart[i].quantity + #form.qnt#>
<cfset newitem = 1>
<cfbreak>
</cfif>
</cfloop>


<cfif newitem EQ 0>
<cfset temp = arrayAppend(session.shoppingcart, structNew())>
<cfset session.shoppingcart[arrayLen(session.shoppingcart)].productID = #form.id#>
<cfset session.shoppingcart[arrayLen(session.shoppingcart)].name = #form.name#>
<cfset session.shoppingcart[arrayLen(session.shoppingcart)].quantity = #form.qnt#>
<cfset session.shoppingcart[arrayLen(session.shoppingcart)].price = #form.p#>
</cfif>

<script>
self.location="cart.cfm";
</script>


This page goes hand-in-hand with the cart.cfm page. This is where we get all of our products to display! After the user clicks the "Add to Cart" button, this script actually puts the product and all of its contents as a new structure into our shopping cart aray.

The first thing it does is check to see if a shopping cart array exists. If not, it creates that new array.

Then, it loops over our cart and checks to see if that product is already in the shopping cart, using its ID number as a reference. If the product is in fact in the cart, it adds the quantity number as entered on the product display page to the current quantity inside the cart.


Using a variable called "newitem" it checks to see if we already updated the quantity of an existing product. If not, we have to add this product to the cart. We set up our new structure and insert all of the new values into their positions. You'll see that the new product number is designated by using the arrayAppend function, creating a free position for our new product to be entered. This adds a new spot at the end of the array for our product to be entered.

Finally, we send the user to cart.cfm so they can see they're cart with its new quantity or new products.

Now that we have our products in the cart, there's only one thing left to do... make those people pay! You'll notice the cart.cfm page has links to checkout.cfm. You can see all the checkout scripting in part 3.


If you have any questions or comments feel free to e-mail me at any time.
Part 1 - Part 2 - Part 3
About This Tutorial
Author: Michael Bamberger
Skill Level: Intermediate 
 
 
 
Platforms Tested: CFMX
Total Views: 109,402
Submission Date: August 31, 2004
Last Update Date: June 05, 2009
All Tutorials By This Autor: 3
Discuss This Tutorial
  • Create Shopping Cart

  • how do I add more items to the cart... do i add a link to circle back to the product_display.cfm page from the cart.cfm? Right now it only adds the item that a person clicks "Add to Cart" for. The other items can not be added unless a new product_display.cfm is launched. thanks, Dave

  • Any idea why I am getting this error: Object of type class java.lang.String cannot be used as an array The error occurred in D:\...: line 76 74 : 75 : 76 : 77 :

  • checkout_signin.cfm?

  • shopping cart always shows "Empty" Can you help me my cart always shows that it is empty. thank you

  • I made a few changes to accomodate some things I need, however when I try and add additional information to populate the cart I keep getting Element Undefined Errors. Product Display - ----I added the above line---- Cart - #session.shoppingcart[i].Show_ID# ----I try and reference it on the above line---- #session.shoppingcart[i].name# #DollarFormat(session.shoppingcart[i].price)# #session.shoppingcart[i].quantity# #DollarFormat(total[i])# Add to Cart ---I added the above line----- self.location="product_display.cfm"; Any help would be appreciated, thanks.

  • Hi there, i followed the shopping cart with array part II tutorial, and when i ran my application, add items into cart, the cart.cfm always showed "Your shopping cart is currently empty" eventhough it's not empty. Can you help me to trouble shoot this problem? I go from product page first, then click on a product, customer will see the detail page for that product, on this detail page, he can click on "Add to Cart" and will see the shopping cart contents.

  • this is a great tutorial. Really easy to implement and goes over the details well. The only thing i would change is adding a order_detail table that keeps track of the individual items and quantities in a database. This will make future reporting a bit easier, but this is a GREAT starting spot. If you want suggestions for adding the order_detail part and a bit of reporting email me.

Advertisement

Sponsored By...
Mobile App Development (IOS, Android, Cordova, Phonegap, Objective-C, Java) - Austin, Texas Mobile Apps - Touch512, LLC.