<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Webcodez - The database of web programming tutorials &#187; Shopping Cart System</title>
	<atom:link href="http://www.webcodez.net/tag/shopping-cart-system/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.webcodez.net</link>
	<description>Archive of tutorials on php,mysql,Javascript,html,css and other coding languages as well as code-snippets.</description>
	<lastBuildDate>Tue, 18 May 2010 16:43:49 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Basic Shopping Cart System</title>
		<link>http://www.webcodez.net/php-mysql/basic-shopping-cart-system/</link>
		<comments>http://www.webcodez.net/php-mysql/basic-shopping-cart-system/#comments</comments>
		<pubDate>Sat, 23 Jan 2010 10:50:20 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[arrays]]></category>
		<category><![CDATA[for loop]]></category>
		<category><![CDATA[foreach loop]]></category>
		<category><![CDATA[GET]]></category>
		<category><![CDATA[net script]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[Shopping Cart System]]></category>
		<category><![CDATA[variables]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=192</guid>
		<description><![CDATA[NOTE: This is a tutorial on creating a basic shopping cart system and giving an idea on how to create the basic functions of a shopping cart system and does not explain the securing of user input or checking whether the added products &#8216;exist&#8217; as that all depend on what products you offer and so [...]]]></description>
			<content:encoded><![CDATA[<p><strong>NOTE:</strong> This is a tutorial on creating a basic shopping cart system and giving an idea on how to create the basic functions of a shopping cart system and does not explain the securing of user input or checking whether the added products &#8216;exist&#8217; as that all depend on what products you offer and so database interactions which are not used in the basic shopping cart system yet as they only explain the basic functions to handle it. Therefore another tutorial will be created for creating an advanced total shopping cart system, as soon as possible.</p>
<h3>Tutorial Content</h3>
<p>First off, this tutorial is meant for creating a very basic shopping cart system. Not offering a copy-pastable setup script. It will show you how you can create the following functions for your shopping cart system:</p>
<p>* Adding products ( stored into session arrays )</p>
<p>* Removing products</p>
<p>* Empty/Clear shopping cart</p>
<p>* Retrieving all products ( from session )</p>
<p>* Changing amount on products</p>
<p>We&#8217;ll just be creating a simple basic shopping cart system now that is cappable of these 4 things. We won&#8217;t be using classes, OOP yet, which we&#8217;ll be doing in the next tutorial ( Advanced Shopping Cart System ). Having mentioned this all &#8211; let&#8217;s start.</p>
<h3>Shopping Cart System File</h3>
<p><strong>Shpping Cart System PHP File and the structure of the session array containing all products of the shopping cart</strong></p>
<p>What I usually start off with is creating the files we&#8217;ll be using. Which is only one:</p>
<p>* cart.php</p>
<p>As sessions are an important part of this system we&#8217;ll obviously need to set session_start first to be able to use session variables.</p>
<p><strong>File: cart.php</strong></p>
<pre name="code" class="php:nogutter">&lt;?php
session_start();

?&gt;</pre>
<p>We&#8217;ll be using the session $_SESSON['sc'] to store all products into (sc = shoppingcart ). So if it isn&#8217;t there yet, we&#8217;ll make it an empty array:</p>
<pre name="code" class="php:nogutter">&lt;?php
session_start();

if(!isset($_SESSION['sc']))
   $_SESSION['sc'] = array();
?&gt;
</pre>
<p>isset is a function used to check if the variable or array has been set/defined. We put a ! before it to check if it has NOT been set yet. The array will be of the following structure (2 products for example, first product gets index 0 ( [0] ), second index 1, etc. ):</p>
<pre name="code" class="php:nogutter">$_SESSION['sc'] = array(
         [0] =&gt; array("ID" =&gt; product_id, "amount" =&gt; product_amount),
         [1] =&gt; array("ID" =&gt; product_id, "amount" =&gt; product_amount),
         ... etc ... );
</pre>
<p>So for each new product, an array is added to the array &#8217;sc&#8217;, containing the product ID and amount in cart. So for example to add a test product to the shopping cart at start:</p>
<pre name="code" class="php:nogutter">&lt;php
 session_start();

if(!isset($_SESSION['sc']))
   $_SESSION['sc'] = array();

//add test product if not already exists
if(!$_SESSION['sc'][0])
$_SESSION['sc'][0] = array("ID" =&gt; 1, "amount" =&gt; 10);
?&gt;
</pre>
<p>Now we added a test product, ID of the product is 1 and the amount we set to 10.</p>
<h3>Retrieve Current Products</h3>
<p><strong>Retrieve the products that are currently inside the shopping cart</strong></p>
<p>With this info we can already make it retrieve the current products in the shopping cart. We&#8217;ll do this using a foreach loop. First however, we&#8217;ll need to check if there are any products in it at all, otherwise say it&#8217;s empty. We use the function count to count the amount of sub-variables or sub-arrays in this case, for the array $_SESSION['sc']. As each sub-array represents a product, we can tell if there are any products by counting them using the count function. We&#8217;ll store that in a variable $products. If it&#8217;s a value greater than 0 ( if there are any sub-arrays/products ), retrieve the products:</p>
<pre name="code" class="php:nogutter">$products = count($_SESSION['sc']);
if($products &gt; 0) { //if there are more than 0 products in the shopping cart

    //... retrieve products ...

}else{

   echo "Empty";

}
</pre>
<p>We&#8217;re now going to use 2 loops to retrieve the products. The first loop is a for loop which we use to get all products ( which are all sub-arrays ).</p>
<pre name="code" class="php:nogutter">for($curr=0;$curr&lt;$products;$curr++) {

}
</pre>
<p>What the for loop basicly does here is set a variable $curr to 0 ( the first index -&gt; first product of the array ), which represents the product $_SESSION['sc'][0]. Then it executes the loop ( nothing yet inside ) for that product ( which is $_SESSION['sc'][0] in the first loop execution time, but which is always = $_SESSION['sc'][$curr] ). After executing the loop for that product, it checks whether there are any other products by checking if $curr ( the current index ) is smaller than the amount of products. Which is equal to the last index + 1, as the first product starts with the index 0 instead of 1, and counting products start by 1 of course. So if there are any more products, it gets the next one which has the next array index. As the previous index = $curr, the next one is $curr++, which increases the current index by 1.</p>
<p>Ok so now we can handle all products inside this loop. The current product will be $_SESSION['sc'][$curr] as $curr contains the index of the current product. But as each array got it&#8217;s own sub-array (containing the ID and Amount) we need to use a forloop. This will get both the ID and Amount values of the products (sub-arrays):</p>
<pre name="code" class="php:nogutter">for($curr=0;$curr&lt;$products;$curr++) {

    foreach( $_SESSION['sc'][$curr] as $key =&gt; $value ) {

        echo $key.":".$value." &lt;br /&gt;";

    }

}
</pre>
<p>We know each product has it&#8217;s own index ( $curr ) and as value a sub-array like this:</p>
<blockquote><p>array(&#8220;ID&#8221; =&gt; prod_id, &#8220;amount&#8221; =&gt; prod_amount)</p></blockquote>
<p>So what we do is use a foreach loop to get the indexes ( ID and Amount ) of the array/product and the values of them (product id and product amount ). Then we echo them like this:</p>
<pre name="code" class="php:nogutter">        echo $key.":".$value." &lt;br /&gt;";
</pre>
<p>which outputs:</p>
<blockquote><p>ID: product id here<br />
amount: product amount here</p></blockquote>
<p>for each product it found in the for loop.</p>
<p>Let&#8217;s put this all together:</p>
<pre name="code" class="php:nogutter">&lt;php
  session_start();

 if(!isset($_SESSION['sc']))
    $_SESSION['sc'] = array();

//removed test product

$products = count($_SESSION['sc']);
if($products &gt; 0) { //if there are more than 0 products in the shopping cart

   for($curr=0;$curr&lt;$products;$curr++) {

    foreach( $_SESSION['sc'][$curr] as $key =&gt; $value ) {

         echo $key.":".$value." &lt;br /&gt;";

     }
   }

}else{

   echo "Empty";

}
</pre>
<p>Now we completed the first function for our shopping cart system: Retrieving all products. 4 more to go!</p>
<h3>Function &#8211; Add Products</h3>
<p><strong>Function to add products to the shopping cart</strong></p>
<p>Let&#8217;s start with creating a function to add a product. This shouldn&#8217;t be such a big hassle having discusses all of the structure of the shopping cart array and product sub-arrays. What we basicly need to do is add a new sub-array with the index of the last product&#8217;s index + 1 and create the sub array with the product ID and amount. We&#8217;ll have a look at the code:</p>
<pre name="code" class="php:nogutter">    $new = count($_SESSION['sc']);
    $_SESSION['sc'][$new] = array("ID" =&gt; $_GET['p'], "amount" =&gt; 1);
</pre>
<p>So $new contains the new array id for the new product. This is equal to the amount of products because, as mentioned before, product 1 has the index 0. So the last product&#8217;s index is the amount of products -1, and we just count one plus that and we&#8217;d get our new product index. And we all know -1+1 = 0 So we can leave that out and just count the products and use that number as the new index for the new product added.<br />
Then we add the product by creating a sub-array with the id and amount. The ID is here set to $_GET['p'], so cart.php?p=1 would add product id 1 ($_GET['p'] = 1).</p>
<p>Though we could now add one product twice, which would bug the system as there&#8217;s also already an amount set inside the product sub-array (ID and Amount is set for each product). So we need to check whether the product isn&#8217;t already in the shopping cart array. We can do this with the following for loop:</p>
<pre name="code" class="php:nogutter">for($index=0;$index&lt;$products;$index++) {

    if($_GET['p'] == $_SESSION['sc'][$index]['ID']) {

        $index_exists = true;

    }

}
</pre>
<p>Let&#8217;s go through this code. What it basicly does is set a variable $index to 0 ( the first product&#8217;s index ) and execute the loop for each index (product in the shopping cart array), which are the indexes 0 &#8211; ($products-1) in other words: $index&lt;$products. Then for each product we need to check if the ID ($_SESSION['sc'][$index]['id']) is equal to the id of the product requested to be added ($_GET['p']). If this is the case for any of the products, $index_exists will be set to true. So when $index_exists is set to true, there was a product found with the ID requested to be added. In that case the product was already added to the shopping cart earlier.</p>
<p>Thus we just need to check if $index_exists is equal to true, if so: the product is already in the shopping cart -&gt; show error message:</p>
<pre name="code" class="php:nogutter">if($index_exists) {

    echo "&lt;p&gt;Product already added &lt;/p&gt;";

}else{

    ///... else - product was not added earlier already -&gt; add the product

}
</pre>
<p>Otherwise ( else ) the product wasn&#8217;t found in the shopping cart so it will be added successfully. We can there put our &#8216;product add&#8217; code:</p>
<blockquote><p>$new = count($_SESSION['sc']);<br />
$_SESSION['sc'][$new] = array(&#8220;ID&#8221; =&gt; $_GET['p'], &#8220;amount&#8221; =&gt; 1);</p></blockquote>
<p>=&gt;</p>
<pre name="code" class="php:nogutter">if(isset($index_exists)) {

    echo "&lt;p&gt;Product already added &lt;/p&gt;";

}else{

    ///... else - product was not added earlier already -&gt; add the product
    $new = count($_SESSION['sc']);
    $_SESSION['sc'][$new] = array("ID" =&gt; $_GET['p'], "amount" =&gt; 1);

}
</pre>
<p>Let&#8217;s put that all together again:</p>
<pre name="code" class="php:nogutter">&lt;php
   session_start();

  if(!isset($_SESSION['sc']))
     $_SESSION['sc'] = array();

 $products = count($_SESSION['sc']);
 if($products &gt; 0) { //if there are more than 0 products in the shopping cart

   for($curr=0;$curr&lt;$products;$curr++) {

     foreach( $_SESSION['sc'][$curr] as $key =&gt; $value ) {

          echo $key.":".$value." &lt;br /&gt;";

      }
   }

 }else{

    echo "Empty";

 }

if($_GET['act'] == 'add' AND $_GET['p']) {

for($index=0;$index&lt;$products;$index++) {

    if($_GET['p'] == $_SESSION['sc'][$index]['id']) {

        $index_exists = true;

    }

}

if(isset($index_exists)) {

     echo "&lt;p&gt;Product already added &lt;/p&gt;";

 }else{

     ///... else - product was not added earlier already -&gt; add the product
    $new = count($_SESSION['sc']);
      $_SESSION['sc'][$new] = array("id" =&gt; $_GET['p'], "amount" =&gt; 1);

 }

}

?&gt;
</pre>
<p>We used an if loop which checks if $_GET['act'] == &#8216;add&#8217; and $_GET['p'] exists, which is the case when you go to the url like &#8216;cart.php?act=add&amp;p=product_id&#8217;. So when you link the user there, the product_id will be added to the shoppingcart.</p>
<p>Example link:</p>
<pre class="html:nogutter">&lt;a href='cart.php?act=add&amp;p=1'&gt;Add product #1&lt;/a&gt;
</pre>
<h3>Function &#8211; Clear Shopping Cart</h3>
<p><strong>Function to clear the shopping cart</strong></p>
<p>Allright, now we&#8217;ll create a function to clear the shopping cart. Which just unsets the whole session &#8217;sc&#8217;:</p>
<pre name="code" class="php:nogutter">if($_GET['act'] == 'clear') {

   unset($_SESSION['sc']);

}
</pre>
<p>We use the function unset to unset the session shopping cart. We&#8217;ll do this when the user requests the url cart.php?act=clear, as in that case the GET variable &#8216;act&#8217; has = &#8216;clear&#8217; ($_GET['act'] = &#8216;clear&#8217;). Which it checks in the if loop. So you can make a link to that url to make it clear the shopping cart. Like:</p>
<pre class="html:nogutter">&lt;a href='cart.php?act=clear'&gt;Empty Shopping Cart&lt;/a&gt;
</pre>
<h3>Function &#8211; Update Products</h3>
<p><strong>Function to update the amount of each product of the shopping cart</strong></p>
<p>Allright, now we&#8217;ve came to the last function which is to change the amount of a product. Which is just changing the sub-variable &#8216;amount&#8217; of the array $_SESSION['sc'][product_array_id]. For example:</p>
<pre name="code" class="php:nogutter">$_SESSION['sc'][0]['amount'] = 10;
//changes the product with array index 0 - sets the amount sub-variable of the product to 10.
</pre>
<p>We&#8217;ll need a form to make the user fill in an amount for a product. For each product we&#8217;ll need to make this form ( so the user can added the amount for each product ). So we&#8217;ll need to add this form inside the loop where it retrieves all products in the shopping cart. Which was the following code ( remember? ) :</p>
<pre name="code" class="php:nogutter">   for($curr=0;$curr&lt;$products;$curr++) {

      foreach( $_SESSION['sc'][$curr] as $key =&gt; $value ) {

           echo $key.":".$value." &lt;br /&gt;";

       }

   }
</pre>
<p>Which we created in the beginning of the tutorial. We&#8217;re going to add this form to it:</p>
<pre name="code" class="php:nogutter">    echo "&lt;form method='POST' action='cart.php?aid=".$curr."'&gt;&lt;p&gt;
Change amount: &lt;input type='text' name='amount' value='".$_SESSION['sc'][$curr]['amount']."'&gt;
&lt;input type='submit' name='submit' value='update'&gt;
&lt;/form&gt;";
</pre>
<p>Let&#8217;s have a look at that form. It uses the method POST, which means it puts all user input into $_POST['form_field_name'] variables when the form is submitted. It goes to the page &#8216;cart.php?aid=&#8221;.$curr.&#8221;&#8216; which means it creates the GET variable $_GET['aid'] and sets it equal to $curr, which contains the array index of the current product that&#8217;s been updated/changed the amount of. Then we&#8217;ve got one field named &#8216;amount&#8217; which has the value of $_SESSION['sc'][$curr]['amount'], which is the amount of the current product ($_SESSION['sc'][$curr] is the current product sub-array containing amount and ID index, we take the ['amount'] sub-variable).</p>
<p>Put it together:</p>
<pre name="code" class="php:nogutter">   for($curr=0;$curr&lt;$products;$curr++) {

       foreach( $_SESSION['sc'][$curr] as $key =&gt; $value ) {

            echo $key.":".$value." &lt;br /&gt;";

        }

    echo "&lt;form method='POST' action='cart.php?aid=".$curr."'&gt;&lt;p&gt;
Change amount: &lt;input type='text' name='amount' value='".$_SESSION['sc'][$curr]['amount']."'&gt;
&lt;input type='submit' name='submit' value='update'&gt;
&lt;/form&gt;";

     }
</pre>
<p>Let&#8217;s update the old for loop and put it all together:</p>
<pre name="code" class="php:nogutter"> &lt;php
    session_start();

   if(!isset($_SESSION['sc']))
      $_SESSION['sc'] = array();

  $products = count($_SESSION['sc']);
  if($products &gt; 0) { //if there are more than 0 products in the shopping cart

####UPDATED####

    for($curr=0;$curr&lt;$products;$curr++) {

        foreach( $_SESSION['sc'][$curr] as $key =&gt; $value ) {

             echo $key.":".$value." &lt;br /&gt;";

         }

    echo "&lt;form method='POST' action='cart.php?aid=".$curr."'&gt;&lt;p&gt;
 Change amount: &lt;input type='text' name='amount' value='".$_SESSION['sc'][$curr]['amount']."'&gt;
 &lt;input type='submit' name='submit' value='update'&gt;
 &lt;/form&gt;";

      }

  }else{

     echo "Empty";

  }

if($_GET['act'] == 'add' AND $_GET['p']) {

for($index=0;$index&lt;$products;$index++) {

     if($_GET['p'] == $_SESSION['sc'][$index]['id']) {

         $index_exists = true;

     }

 }

if(isset($index_exists)) {

      echo "&lt;p&gt;Product already added &lt;/p&gt;";

  }else{

      ///... else - product was not added earlier already -&gt; add the product
     $new = count($_SESSION['sc']);
       $_SESSION['sc'][$new] = array("id" =&gt; $_GET['p'], "amount" =&gt; 1);

  }

}

###########ADDED############

if($_GET['act'] == 'clear') {

   unset($_SESSION['sc']);

}

?&gt;
</pre>
<p>Ok, so when the user tries to update the amount of a product, the variable $_GET['aid'] will be containing the array index of the product and $_POST['amount'] will contain the user filled in amount in the form field &#8216;amount&#8217;.</p>
<p>To check if the user tried to change the amount of a product, we simply check if $_POST['amount'] exists and if not empty:</p>
<pre name="code" class="php:nogutter">if(!empty($_POST['amount'])) {

   //update amount

}
</pre>
<p>Let&#8217;s put the array id ($_GET['aid']) inside a variable $array_id and the amount the user filled in for that product ($_POST['amount']) inside a variable $amount:</p>
<pre name="code" class="php:nogutter">    $array_id = $_GET['aid'];

    $amount = $_POST['amount'];
</pre>
<p>Now we need to change the amount of the product with the index $array_id. As all products are in the array $_SESSION['sc'], the product is $_SESSION['sc'][$array_id]. And to change the amount of that product we need to change the sub-variable &#8216;amount&#8217;. So it becomes: $_SESSION['sc'][$array_id]['amount'].<br />
We&#8217;ll set it equal to the user input = $amount, so:</p>
<pre name="code" class="php:nogutter">if(!empty($_POST['amount'])) {

   //update amount

    $array_id = $_GET['aid'];

     $amount = $_POST['amount'];

    $_SESSION['sc'][$array_id]['amount'] = $amount;

}
</pre>
<h3>Shopping Cart System &#8211; End Result</h3>
<p>We put it all together and we&#8217;re done with our &#8220;basic &#8221; shopping cart system!</p>
<p><strong>File: cart.php</strong></p>
<pre name="code" class="php:nogutter">  &lt;php
session_start();

if(!isset($_SESSION['sc']))
   $_SESSION['sc'] = array();

$products = count($_SESSION['sc']);

###########RETRIEVE PRODUCTS FUNCTION############

if($products &gt; 0) { //if there are more than 0 products in the shopping cart

   for($curr=0;$curr&lt;$products;$curr++) {

    foreach( $_SESSION['sc'][$curr] as $key =&gt; $value ) {

        echo $key.":".$value." &lt;br /&gt;";

    }

    echo "&lt;form method='POST' action='cart.php?aid=".$curr."'&gt;&lt;p&gt;
Change amount: &lt;input type='text' name='amount' value='".$_SESSION['sc'][$curr]['amount']."'&gt;
&lt;input type='submit' name='submit' value='update'&gt;
&lt;/form&gt;";

   }

}else{

   echo "Empty";

}

###########ADD FUNCTION############
if($_GET['act'] == 'add' AND $_GET['p']) {

for($index=0;$index&lt;$products;$index++) {

    if($_GET['p'] == $_SESSION['sc'][$index]['ID']) {

        $index_exists = true;

    }

}

if($index_exists) {

    echo "&lt;p&gt;Product already added &lt;/p&gt;";

}else{

    ///... else - product was not added earlier already -&gt; add the product
    $new = count($_SESSION['sc']);
    $_SESSION['sc'][$new] = array("ID" =&gt; $_GET['p'], "amount" =&gt; 1);
    echo "&lt;p&gt;".$_GET['p']." ID added for index ".$new."&lt;/p&gt;";

}

}

###########CLEAR FUNCTION############

if($_GET['act'] == 'clear') {

   unset($_SESSION['sc']);

}

###########ADDED - UPDATE FUNCTION############

if(!empty($_POST['amount'])) {

   //update amount

    $array_id = $_GET['aid'];

    $amount = $_POST['amount'];

    echo "&lt;p&gt;array id:".$array_id." and amount: ".$amount." and product id: ".$_SESSION['sc'][$array_id]['ID']."&lt;/p&gt;";

    $_SESSION['sc'][$array_id]['amount'] = $amount;
    echo $_SESSION['sc'][$array_id]['amount'];

}

?&gt;
</pre>
<p>This system was more complicated to explain because of the arrays and sub-arrays and because of it&#8217;s somewhat longer size ( script ). But hope you learnt something!</p>
<p>Cheers,<br />
Admin.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/basic-shopping-cart-system/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
