Join us on Facebook

Please wait..10 Seconds Cancel

1.03.2014

// // Leave a Comment

Create a Shopping Cart using PHP & View Detail About How It Work


 How It Works!!!
=>        To implement virtual shopping cart function we use sessions. For each visitor new session is initiated. We can use a simple array to store product, which customer has added to his shopping cart. If visitor clicks "Add to cart" button, following PHP code is executed (includes/shopping_cart.php):

<?php 
 //add product to cart with productID=$add2cart 
    { 
        $q = db_query("select in_stock from ".PRODUCTS_TABLE." where productID='".(int)$_GET["add2cart"]."'") or die (db_error()); 
        $is = db_fetch_row($q); $is = $is[0]; 

        //$_SESSION['gids'] contains product IDs 
        //$_SESSION['counts'] contains item quantities ($_SESSION['counts'][$i] corresponds to $_SESSION['gids'][$i]) 
        //$_SESSION['gids'][$i] == 0 means $i-element is 'empty' (does not refer to any product) 
        if (!isset($_SESSION["gids"])) 
        { 
            $_SESSION["gids"] = array(); 
            $_SESSION["counts"] = array(); 
        } 
        //check for current product in visitor's shopping cart content 
        $i=0; 
        while ($i 

?>


Here we use two array to store products in the shopping cart: $_SESSION["gids"] contains productID values of the products which are currently in the customer's shopping cart. $_SESSION["counts"] contains item quantities information - how many items of a certain product are there in customer's cart. Such method allows easily add products to cart and remove them. Here is how you can remove a product from cart:


<?php 

if (isset($_GET["remove"]) && (int)$_GET["remove"] > 0) //remove product with productID == $remove 
    { 
        $i=0; 
        while ($i<count($_SESSION["gids"]) && $_SESSION["gids"][$i] != (int)$_GET["remove"]) 
            $i++; 
        if ($i<count($_SESSION["gids"])) 
            $_SESSION["gids"][$i] = 0; 
    } 

?>


And if you would like to clear cart content (remove all products from cart), simple execute this code:


<?php 
  unset($_SESSION["gids"]); 
  unset($_SESSION["counts"]); 

?>


It's that easy.

Displaying shopping cart content 

To display shopping cart content to customer, we only load cart content from session to Smarty variable, and then it can be presented to customer using this Smarty template (shopping_cart.tpl.html):

{section loop=$cart_content name=i}

<tr>

<td>{if $cart_content[i].product_code ne ""}[{$cart_content[i].product_code}] {/if}{$cart_content[i].name}</td>

<td><input type="text" name="count_{$cart_content[i].id}" size="5" value="{$cart_content[i].quantity}"></td>

<td>{$cart_content[i].cost}</td>

<td>

<a href="index.php?shopping_cart=yes&remove={$cart_content[i].id}"><img src="images/remove.jpg" border="0" alt="{$smarty.const.DELETE_BUTTON}"></a>

</td>

</tr>

{/section}


 

0 comments:

Post a Comment