E-Commerce Exercise 3

E-commerce Shopping Cart

 

  1. The shopping cart will have two major duties.  The first duty is to add items to the shopping cart.  The second duty is to update the quantity of items in the cart.
  2. We will decide what action to perform by passing a variable called action to the file in the URL (same as GET method).  Steps 3-4 describe how we will add an item to the shopping cart.  Steps 5-8 describe how the update_cart action.  Steps 9-10 describe the function used to display the shopping cart.  The general pseudocode for cart.php is as follows:

 

if ($_GET[action] == "add_to_cart")

{

           execute code here for adding an item to the shopping cart;

}

elseif ($_GET[action] =="update_cart")

{

           execute code here for updating the quantity of an item already in the cart;

}

 

display the table;

 

  1. The first duty of adding an item to the cart is easy.  Basically, if the cart is empty, the array location is 0.  Otherwise we are going to add the item to the end of the cart.  If the item is already in the cart, the user needs to use the update_quantity method instead of the add_to_cart method.  Here is the pseudocode for adding an item to the cart:

 

$count = # of items already in the shopping cart;

if (count == 0)

{

           insert item_number is session cart_items array;

           insert 1 for the quantity in the session cart_quantities array;

}

elseif (item_number is NOT already in the cart_items array)

{

           add the item_number to the end of the cart_items array;

           add 1 to the end of the cart_quantities array;

}

else

{

           if the previous two conditional statements did not evaluate to TRUE, then we know the cart isn’t empty

           and we know that the item is already in the shopping cart.  We can either display a message telling the

           user to use the update quantity button or do nothing (which is what my sample code does);

}

 

  1. The actual code that goes to the pseudocode is as follows:

 

    // The count() function returns how many items are in an array

           $count = count($_SESSION[cart_items]);

          

           // If the shopping cart was empty and we are inserting

           // the first item, then follow this code

           if ($count== "0")

           {

                      $_SESSION[cart_items][0] = $_GET[item_number];

                      $_SESSION[cart_quantities][0] = 1;

           }

 

           // If the shopping cart has items in it, but does not contain the current item

           // being added, then we will add the item to the end of the array

           // and put make it's quantity 1

           elseif (!in_array($_GET[item_number],$_SESSION[cart_items]))

           {

                      $_SESSION[cart_items][$count]=$_GET[item_number];

                      $_SESSION[cart_quantities][$count]="1";

           }

          

           // If the item is already in the shopping cart, do nothing

           else

           {}

 

  1. The second duty is a bit more complex.  Updating the shopping cart will include updating the quantity array.  The easiest way of updating arrays is to use a built in php function called array splice.  The problem with this idea that if the user clicks refresh after doing an update with a new quantity of 0, the array will be spliced again and a different item will be erased from the shopping cart arrays.
  2. To correct this problem, if the new_qty <= 0,the sample website will first find the item to be updated in the shopping.  The $index variable will hold the index of the item to erased from the arrays.  Then the arrays[$index] = 0 will be used to mark the array splice will occur.
  3. If the new_qty > 0, we will simply replace the cart_quantities($index) equal to the user input.  The following is the pseudocode for updating the cart:

 

If (new_qty <= 0)

{

           $index = index of item to update (search_array() function will give us the index);

           set the cart_items[$index] =0;

           set the cart_quantities{$index] = 0;

}

else

{

           $index = index of item to be updated;

           set the cart_quantities[$index] = new_qty;

}

 

if (“0” is in the array, then splice the array (effectively removes the item from the array))

{

           splice both the cart_items & cart_quantities arrays to remove the item from the arrays;

}

 

 

  1. The actual php code that corresponds to the pseudocode is as follows:

 

elseif($_GET[action]=="update_cart")

{

           // If the new_qty is less than zero, we need to remove the item

           // from the users shopping cart

           if ($_GET[new_qty] <= "0")

           {

                      // array_search() function will return the index of

                      // the item we are trying to remove from the shopping cart

                      $index = array_search($_GET[which_item],$_SESSION[cart_items]);

                     

                      // If we successfully find an index, then set the quantity and item number = 0

                      // We will actually remove the items from the array later

                      if (!empty($index))

                      {

                                $_SESSION[cart_items][$index] = 0;

                                $_SESSION[cart_quantities][$index] = 0;

                      }

                     

                      // $index could be "0" and actually mean that it found the item in location[0]

                      // or it could be "zero", meaning that it didn't find the item in the array.

                      // Either way, !empty($index) would not evaluate to true.

                      // The in_array(function) will return true if the item we are looking for is in

                      // the $_SESSION[cart_items] array.  If it is, then we know the index is 0.

                      elseif (in_array($_GET[which_item],$_SESSION[cart_items]))

                      {

                                $_SESSION[cart_items][0] = 0;

                                $_SESSION[cart_quantities][0] = 0;

                      }

           } // end if(new_qty <=0) statement

 

           // If the new_qty > 0, then we simply need to update the quantity in the

           // $_SESSION[cart_quantities][] array

           else

           {

                      $index = array_search($_GET[which_item],$_SESSION[cart_items]);

                      $_SESSION[cart_quantities][$index] = $_GET[new_qty];

           }

           // If there are zero's in the quantity array, then we need to remove that item

           // from both the cart_items & cart_quantities arrays

           if (in_array(0,$_SESSION[cart_quantities]))

           {

                      $remove_index = array_search(0,$_SESSION[cart_quantities]);

                      array_splice($_SESSION[cart_items],$remove_index,1);

                      array_splice($_SESSION[cart_quantities],$remove_index,1);

                     

           }

}

 

  1. After we are done updating or adding items to our shopping cart, we simply need to print out the table of items to the screen.  I wrote the display_table() function and put it in cart_functions.inc.  It’s similar to all of the other table display functions included in this sample website.  The code is long, but most of it is HTML code.  The following is the pseduocode for the display_table() function:

 

 If (The shopping cart is empty)

{

           display Your shopping cart is empty;

}

else

{

           display the HTML code to set up the table;

           for (every item in the shopping cart array)

           {

                      select that row from the database;

                      print out a new row;

                      print out the items in the row;

                      $total_price = $total_price + this_item_price * this_item_qty

           }

           print out the $total_price row;

}

 

10.    The actual code to display the shopping cart table is as follows:

 

// Function to display the Shopping Cart

function display_table()

{

           echo "<H1>Bobby's CD Shopping Cart</H1>\n";

           // If there are no items in the shopping cart, then display a message

           // warning the user their shopping cart is empty

           if (empty($_SESSION[cart_items]))

           {

                      echo "Your shopping cart is empty<br>";

           }

           // If the users shopping cart has items (i.e. not empty)

           // Then display the items

           else

           {

                      // Here is the HTML code to set up the table

                      ?>

                      <TABLE BORDER="1">

                      <TR><TH>Artist</TH><TH>CD Name</TH><TH>Price</TH><TH>Quantity</TH><TH>Update Quantity</TH></TR>

                      <?

                     

                      // Connect to the database

                      $dbcnx = mysql_connect("localhost", "bobby","bobby_passwd") or die("Could not connect to the database.");

                      mysql_select_db("bobby",$dbcnx) or die("Can not select database");

 

                      // Run through the cart_items array

                      for ($i=0; $i< count($_SESSION[cart_items]); $i++)

                      {

                                // Run the mySQL query to get the artist, cd_name, and price from the database

                                $query = "SELECT artist,cd_name,price FROM cd_store WHERE item_number=\"{$_SESSION[cart_items][$i]}\"";

                                $query = stripslashes($query);

                                $result = mysql_query($query) or die(mysql_error());

                                $number_cols = mysql_num_fields($result);

                     

                                while ($row = mysql_fetch_row($result))

                                {

                                           // At the beginning of every row, print out the correct

                                           // HTML code to start a new row

                                           echo "<tr>";

                                           for ($j=0; $j < $number_cols; $j++)

                                           {

                                                      // Print out a new cell HTML code

                                                      echo "<td>";

                                                     

                                                      // If $j==2 then we are printing out the price

                                                      // and we want to put a "$" in front of the

                                                      // data from the database

                                                      if ($j == "2")

                                                      {         

                                                                 echo "\$";

                                                                 print_r($row[$j]);

                                                      }

                                                     

                                                      // If $j != 2 then we just want to print out the

                                                      // information from the database normally

                                                      else

                                                      {

                                                                 print_r($row[$j]);

                                                      }

                                                      echo "</td>";

                                           }

 

                                           // Print out the quantity for this item

                                           // Don't for get the "{" & "}" around the $_SESSION[][] array

                                           echo "<td>{$_SESSION[cart_quantities][$i]}";

                                          

                                           // To calculate the total price, we will multiply the quantity of this item

                                           // by the price of this item ($row[2] is the price)

                                           $total_price  += $_SESSION[cart_quantities][$i]*$row[2];

                                           echo "</td>";

                                          

                                           // Display the update cart form for each row

                                           echo "<form action=\"$self\" method=\"GET\"><td valign=\"middle\">

                                           <input type=\"hidden\" name=\"action\" value=\"update_cart\">

                                           <input type=\"hidden\" name=\"which_item\" value=\"{$_SESSION[cart_items][$i]}\">

                                           <input type=\"text\" name=\"new_qty\" size=\"2\">

                                           <input type=\"submit\" value=\"Update Cart\">

                                           </form></td>";

                                           echo "</tr>";

                               

                                } // end while statement

                      }  // end for statement

                     

                      // Print the total price to the screen & end the table

                      echo "<TR><TD COLSPAN=\"3\" ALIGN=\"right\">Total Price:</TD>\n<TD align=\"right\">\$ $total_price</TD>";

                      echo "<TD>&nbsp;</TD></TR></TABLE>\n";

           } // End the else statement

           return 1;

}

 

11.    The cart_functions.inc file also includes the html_headers() & html_footer() functions to display the initial and final HTML.  The functions are found in every .inc file in the sample e-commerce website.

12.    The session_destroy.php file is the “Empty Shopping Cart” link on the shopping cart.  This file will “empty” the users shopping cart by destroying their session.  The source code is provided below or you can download it here.

 

<?php

session_start();

session_destroy();

 

include 'confirm_order_functions.inc';

 

html_headers("Bobby's CD Store - Empty Shopping Cart");

 

echo "Your cart has been emptied<br>";

echo "[ <a href=\"search.php\">Search Again</a> ]";

 

html_footer();

 

?>

 

13.    The source for cart.php and cart_functions.inc can be found:

 

Source for cart.php

Source for cart_functions.inc