Setting up a Summary Cart on Your Site with PHP

Using Mals ecommerce shopping cart in combination with some PHP and HTML it’s possible to integrate a cart summary information box into your site.

Cart Example

This cart summary box could display the current state of the customers order as they browse through your store and would be updated everytime the user adds an additional item using mals shopping cart.

This can be accomplished several ways. This article will explain an approach using PHP and cookies.

STEP 1.

We first need to enable the continue shopping button in the cart setup to include all cart content variables. This option will pass back the necessary information to populate your cart summary box. This feature is available under the Button Styles and Behavior section. Click the checkbox titled "Append cart content vars". This option will append all necessary shopping cart information for you to display in your cart content box. These fields include:

Field name Description
qty
Total number of items in the cart
sub
Subtotal
shp
Current shipping calculation
dis
Discounts, is expressed as a positive number
vch
Fixed value voucher, discount vouchers are included in the dis value.
tax
Current tax value
tot
Total for the order
sd
Session data
 

STEP 2.

We now have access to all the major cart information. Using PHP we will extract the necessary data and display it in our cart summary box. Depending on how your cart is setup, this information will be passed back using either POST or GET. For this example we will assume the POST method is enabled. Accessing POST data in PHP is fairly straightforward:

$tot = "$" . $_POST[‘tot’];  // We append $ to the total from mals and store it in
$tot$qty = number_format($_POST[‘qty’],0); //Number format is used to display qty in whole number format

For this example we will use the ‘qty’ variable and ‘tot’ to display the Total number of items the user has in his cart and the total dollar value of these items. Once we have the data stored in variables we can use the echo command to display them in the appropriate html rows:

<!– Cart Code –>
 <table>
 <tr>
 <th>Cart Contents<</th>
 </tr>

 <tr>
 <td>Items:</td>
 <td align="right"><?php
 $qty = number_format($_POST[‘qty’],0);
 $tot = "$" . $_POST[‘tot’];
 echo $qty;

 ?>
 </td>
 </tr>
 <tr>
 <td>Total:</td>

 <td align="right"><?php
 echo $tot;
 ?>
 </td>
 </tr>
 </table>

 <!– End Cart Code –>

STEP 3.

Unfortunately there are several problems with the above code. The web is a stateless environment – each http request does not have any knowledge about the data in the previous request. So assuming our online store has multiple pages we’ll need a method of persisting the cart information so we can display the cart contents on each page of our online store.

One option for saving data is using COOKIES. PHP can create cookies though the setcookie function, and the $_COOKIE syntax can be used to read cookies. Cookies need to be set before any header information is set. This means they must be located at the top of your page before any HTML or whitespace. For each page of our online store we’ll add the following code at the top of each page:

<?php
if (isset($_POST[‘qty’]))
{
setcookie("qty", $_POST[‘qty’]);
setcookie("tot", $_POST[‘tot’]);
}
?>

The above code checks to see if the POST[‘qty’] variable contains any data. If it does the code sets two cookies called qty and tot. These cookies contain the data that is passed in from $_POST[‘qty’] and $_POST[‘tot’].

Note: If you have multiple pages within your store it would be easier to store this code in a seperate file and use the PHP include command at the top of each page.

STEP 4.

Now there is one more caveat about Cookies. Cookies data values will not be available until the page is reloaded. This isn’t a problem for us though. We already have the data available in the $_POST variable. We only need to use the cookies on each successive page load. This will require a slight modification of our cart contents code:

snip…
<?php
//Check to see if the $_POST qty has data. If it has data we want to use it to display the cart contents information.

if (isset($_POST[‘qty’])) {
  $qty = number_format($_POST[‘qty’],0);
  $tot = "$" . $_POST[‘tot’];
}
//If the $_POST var does not have data let’s check to see if the $_COOKIE qty
has data.
elseif (isset($_COOKIE[‘qty’])) {
  $qty = number_format($_COOKIE[‘qty’],0);
  $tot = "$" . $_COOKIE[‘tot’];
  }
 //If neither have data display 0.
else
  {
  $tot="$" . 0;
  $qty=0;
  }
  echo $qty;
  ?><br>
</td></tr><tr><br><td>Total:</td><br><td align="right"><?php<br>
echo $tot;
?>
…snip
     

STEP 5

Now we are almost done. There is one more issue we need to contend with. What happens when a user completes a purchase and decides to use the RETURN TO STORE link to possibly make another purchase? The ‘return to link’ is a hyperlink which does not include the cart content variables that we enabled in STEP 1. We need a way to figure out the user has completed a purchase and properly reset our cart summary contents. One method is to pass a unique variable in the return to link. In the ‘return to link’ section under cart setup enter the following return to link:

<a href="#">www.yousite/store/index.php?resetcart=1</a>

Now we have to modify our header code we set in STEP 3:

<?php
// Default resetCart variable to NO$resetCart="no";
if (isset($_GET[‘resetcart’])) {
// If the resetcart variable is set that means the user has completed an order. We need to ZERO out the cart content.
setcookie ("qty", 0);
setcookie ("tot", 0);
$resetCart="yes"
// This variable will be used later when printing out the cart contents</span>

}
elseif (isset($_POST[‘qty’]))
{
setcookie("qty", $_POST[‘qty’]);
setcookie("tot", $_POST[‘tot’]);
}
?>

STEP 6

There is one last problem. The cookie we set in step 5 will not become active until the page is reloaded. To get around this we will create a variable called resetCart to track when the cart needs to be reset. We’ll add an additional check to our cart contents code from Step 4:

snip…<?php
  //Check to see if the $_POSTqty has data. If it has data we want to use it to display the cart contents information.</span>

if (isset($_POST[‘qty’])) {
        $qty = number_format($_POST[‘qty’],0);
        $tot = "$" . $_POST[‘tot’];
}

//If the $_POST var does not have data let’s check to see if the $_COOKIE qty has data.
elseif (isset($_COOKIE[‘qty’]) &amp;&amp; $resetCart!="yes")
{// If resetCart is equal to YES that means we should ignore the cookie and display 0 for cart contents
   $qty = number_format($_COOKIE[‘qty’],0);
   $tot = "$" . $_COOKIE[‘tot’];
}
//If neither have data display 0.
else
{
    $tot="$" . 0;
    $qty=0;
}
echo $qty;
?>
…snip

Complete Script Example

Note: as noted by Joe Freejoy, when copyin this script one MUST change all the single “curly” quote marks to regular “apostrophe” marks.

Demo available here

<?php
        $resetCart="no";
        if (isset($_GET[‘r’])) {
                setcookie ("qty", 0);
                setcookie ("tot", 0);
                $resetCart="yes";
        }
        elseif (isset($_POST[‘qty’]))
                        {
                        setcookie("qty", $_POST[‘qty’]);
                        setcookie("tot", $_POST[‘tot’]);
                        }

?>     
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Dye Sub Bulk Ink System for Epson Large Format</TITLE>
<META http-equiv=Content-Type content="text/html; charset=iso-8859-1">
</HEAD>
<BODY bgcolor="#FFFFFF" link="#CC0000">
<table width="100%" border="0" cellpadding="3" cellspacing="3">
  <tr>
    <td width="86%" valign="top">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr valign="top">
          <td> <table width="100%" border="0" cellspacing="0" cellpadding="0">
              <tr>
                <td width="15%"><table width="200" border="0" align="center" cellpadding="2" cellspacing="0" style="border:solid 1px #9C0000">
                    <tr>
                      <th class="small" colspan="2" style="background:#9C0000;color:white"><strong>Cart
                        Contents</strong></th>
                    </tr>
                    <tr class="small">
                      <td>Items:</td>
                      <td align="right">
                        <?php
                                //Gather variables for display
                                if (isset($_POST[‘qty’])) {
                                        $qty = number_format($_POST[‘qty’],0);
                                        $tot = "$" . $_POST[‘tot’];
                                        }
                                elseif (isset($_COOKIE[‘qty’]) && $resetCart!="yes") {
                                        $qty = number_format($_COOKIE[‘qty’],0);
                                        $tot = "$" . $_COOKIE[‘tot’];
                                        }
                                else
                                {
                                        $tot="$" . 0;
                                        $qty=0;
                                 }
                                 echo $qty;
                                  ?>
                      </td>
                    </tr>
                    <tr class="small">
                      <td>Total:</td>
                      <td align="right">
                        <?php
                                echo $tot;
                                ?>
                      </td>
                    </tr>
                    <tr>
                      <td colspan="2" class="small" align="right"><a href="http://ww8.aitsafe.com/cf/review.cfm?userid=A098087&return=<?php echo $_SERVER[‘SERVER_NAME’] . $_SERVER[‘PHP_SELF’]; ?>">
                        View Cart</a> </td>
                    </tr>
                  </table></td>
              </tr>
            </table></td>
        </tr>
      </table>
      <?php
          $returnurl=$_SERVER[‘SERVER_NAME’] . $_SERVER[‘PHP_SELF’];
      ?>
      <table border="0" cellspacing="0" cellpadding="3" class="SrchLst" width="75%" align="center">
        <tr>
          <th width="10%">Model</th>
          <th width="51%">Description</th>
          <th width="13%"> Price</th>
          <th width="13%"> </th>
        </tr>
        <tr>
          <td> <div align="center">BIS7696</div></td>
          <td><a href="http://www.jesseheap.com/dye-sublimation-bulk-ink-refill.php">Epson 7600/9600
            Bulk Ink System</a></td>
          <td><div align="center">$725</div></td>
          <form method="POST" action="http://ww8.aitsafe.com/cf/add.cfm">
            <td> <div align="center">
                <input type="HIDDEN" name="userid" value="A098087">
                <input type="HIDDEN" name="product" value=" Epson 7600/9600 Bulk Ink System ">
                <input type="HIDDEN" name="price" value="725">
                <input type="HIDDEN" name="return" value="<?php echo $returnurl; ?>">
                <input type="HIDDEN" name="units" value="350">
                <input type="hidden" name="shipping_zone" value="inks">
                <input name="SUBMIT"
                        type="image" title="Buy"
                        src="http://www.jesseheap.com/button_buy_now.gif" alt="Buy Ink" width="60" height="14"
                        border=0>
              </div></td>
          </form>
        </tr>
        <tr>
          <td> <div align="center">BIS7898</div></td>
          <td><a href="http://www.jesseheap.com/dye-sublimation-bulk-ink-refill.php">Epson 7800/9800
            Bulk Ink System</a></td>
          <td><div align="center">$399</div></td>
          <form method="POST" action="http://ww8.aitsafe.com/cf/add.cfm">
            <td><div align="center">
                <input type="HIDDEN" name="userid" value="A098087">
                <input type="HIDDEN" name="product" value=" Epson 7800/9800 Bulk Ink System ">
                <input type="HIDDEN" name="price" value="399">
                <input type="HIDDEN" name="return" value="<?php echo $returnurl ?>">
                <input type="HIDDEN" name="units" value="350">
                <input type="hidden" name="shipping_zone" value="inks">
                <input name="SUBMIT"
                        type="image" title="Buy"
                        src="http://www.jesseheap.com/button_buy_now.gif" alt="Buy Ink" width="60" height="14"
                        border=0>
              </div></td>
          </form>
        </tr>
      </table> </td>
  </tr>
</table>
</BODY>
</HTML>
 

Script Limitations

  1. We haven’t set an expiration date/time for any of the cookies we have created. Mal-e cart has a 1 hour timeout set. In order to maintain true synchronization between your summary cart and mals you should fdset a cookie expiration time.
  2. Your cart will not update properly if the user utilizes the back button to return to your site (as opposed to the continue shopping button). Unfortunately there is no apparent workaround since we do not have complete control over the code that resides on Mal-e site.

The End.

That’s it. Your done. To see our live store in action go to our sublimation store. If you have any questions you can email me and I’ll try to help – projects at jesseheap dot com.

About the Author

Jesse Heap maintains several different websites as a hobby including his recent favorite Pastry Site which includes some fantastic pictures of unique and creative wedding cakes.