Shop - Add To Cart

 

If you click on the 'Add To Cart' button on the product detail page you will be redirected to the shopping cart page ( cart.php ). For example if you want to buy Naruto Volume 2 you will go to : cart.php?action=add&p=19.

The code for cart.php is like this :

Source code : cart.php

<?php
require_once 'config.php';
require_once 'cart-functions.php';

$action = (isset($_GET['action']) && $_GET['action'] != '') ? $_GET['action'] : 'view';

switch ($action) {
   case 'add' :
      addToCart();
      break;
   case 'update' :
      updateCart();
      break;
   case 'delete' :
      deleteFromCart();
      break;
   case 'view' :
}

// ... more code here to display the cart content

?>


Since we have action=add in the query string the addToCart() function will be called. In short the function will do these :

  1. Check if the product exist in database
  2. Check if we still have this product in stock ( quantity > 0 )
  3. If the product is already in cart increase the quantity
  4. If not add the product to cart

The addToCart() function is located in library/cart-functions.php and the content can be seen below.

Source code : library/cart-functions.php

function addToCart()
{
   // make sure the product id exist
   if (isset($_GET['p']) && (int)$_GET['p'] > 0) {
      $productId = (int)$_GET['p'];
   } else {
      header('Location: index.php');
   }

   // does the product exist ?
   $sql = "SELECT pd_id, pd_qty
           FROM tbl_product
           WHERE pd_id = $productId";
   $result = dbQuery($sql);

   if (dbNumRows($result) != 1) {
      // the product doesn't exist
      header('Location: cart.php');
   } else {
      // how many of this product we
      // have in stock
      $row = dbFetchAssoc($result);
      $currentStock = $row['pd_qty'];

      if ($currentStock == 0) {
         // we no longer have this product in stock
         // show the error message
         setError('The product you requested is no longer in stock');
         header('Location: cart.php');
         exit;
      }
   }

   // current session id
   $sid = session_id();

   // check if the product is already
   // in cart table for this session
   $sql = "SELECT pd_id
           FROM tbl_cart
           WHERE pd_id = $productId AND ct_session_id = '$sid'";
   $result = dbQuery($sql);

   if (dbNumRows($result) == 0) {
      // put the product in cart table
      $sql = "INSERT INTO tbl_cart (pd_id, ct_qty, ct_session_id, ct_date)
              VALUES ($productId, 1, '$sid', NOW())";
      $result = dbQuery($sql);
   } else {
      // update product quantity in cart table
      $sql = "UPDATE tbl_cart
              SET ct_qty = ct_qty + 1
              WHERE ct_session_id = '$sid' AND pd_id = $productId";

      $result = dbQuery($sql);
   }

   deleteAbandonedCart();

   header('Location: ' . $_SESSION['shop_return_url']);
}

After finish placing an item into the cart this function do something else. It calls deleteAbandonedCart(). I know it's kind of weird to call this function here but currently it is the best place to call it. We actually have at least three options on how and when to delete abandoned:

  1. Call deleteAbandonedCart() when adding a product into cart like shown above
  2. Make a new submodul on admin page where we have a button saying 'Delete All Abandoned Cart'
  3. Using cron job to remove the abandoned cart periodically.

The first option is what i see as the best option right now, because adding an admin submodul requires extra work, and using cron means installing the shop will become a hassle. Before i forget here is what deleteAbandonedCart() look like :

Source code : library/cart-functions.php

function deleteAbandonedCart()
{
   $yesterday = date('Y-m-d H:i:s',
                mktime(0,0,0, date('m'), date('d') - 1, date('Y')));
   $sql = "DELETE FROM tbl_cart
           WHERE ct_date < '$yesterday'";
   dbQuery($sql);
}

We consider a cart is abandoned if it's older than one day. So first we find out what date yesterday was and send a query to database to remove any cart entry where the cart date is less than yesterday date.

Okay, after adding the product and removing all abandoned carts we don't send the customer to the shopping cart page. She will stay on the product detail page. But this time the mini cart on the right side will show the product in her shopping cart.

The mini cart is included from include/miniCart.php. It displays all product currently in shopping cart. It also show the total amount after the shipping cost.

This behaviour ( sending the customer to product page after adding a product ) is actually depend on what kind of shop we're running. If it's a shop where people usually buy more than one kind of product then it's better if we skip showing the shopping cart page and display the product page. But if people on this kind of shop usually only buy one product in a shopping session then it's best if we display the shopping cart page. You just need to modify the redirection to

header('Location: cart.php?action=view');

If you're still not sure where to send the shopper after add to cart there's a discussion thread in Webmasterworld forum discussing this issue, check it out.

Next we start working on the shopping cart page.

 

 

 

 

Online Shop - View Product Detail PHP MySQL Shopping Cart Tutorial : Online Shop - Add To Cart Online Shop - View Shopping Cart
Google
 
Web www.phpwebcommerce.com
 

At long last i'm finally able to update this site. Now the shopping cart can handle payment through paypal. As always you have any critiques, questions, comments or problems about this tutorial please tell me. Click here to send your feedback. And if you like this tutorial please link to this site. It will really help a lot :-)

 

Get custom programming done at ScriptLance.com!

 



PHP MySQL Shopping Cart Tutorial
Copyright © 2005 - 2008 www.phpwebcommerce.com