<?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; POST</title>
	<atom:link href="http://www.webcodez.net/tag/post/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>Retrieving User Input Data</title>
		<link>http://www.webcodez.net/php-mysql/retrieving-user-input-data/</link>
		<comments>http://www.webcodez.net/php-mysql/retrieving-user-input-data/#comments</comments>
		<pubDate>Sat, 27 Feb 2010 14:19:50 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[Forms]]></category>
		<category><![CDATA[if loop]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[user input]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=460</guid>
		<description><![CDATA[In this tutorial we&#8217;ll be retrieving data from form fields. To do this we&#8217;ll first create an example form. We&#8217;re using the POST method to send the form data in the first example. Will later explain what this means, and how we can then retrieve the data from the form fields. Also the GET method [...]]]></description>
			<content:encoded><![CDATA[<p>In this tutorial we&#8217;ll be retrieving data from form fields. To do this we&#8217;ll first create an example form. We&#8217;re using the POST method to send the form data in the first example. Will later explain what this means, and how we can then retrieve the data from the form fields. Also the GET method will be explained in this tutorial later on. For the form we set the action to the file itself ( we call it &#8216;form_handle.php&#8217;, call it anything you like ). </p>
<h3>The Form</h3>
<p><strong>File: form_handle.php</strong></p>
<pre name="code" class="php:nogutter">
&lt;form method="POST" action="fom_handle.php">
 &lt;input type="text" name="test_field">
 &lt;input type="submit" name="submit" value="Send!">
&lt;/form>
</pre>
<p><h3>Handling the form data</h3>
<p>Ok in this form we made 2 fields. One text input field, we named &#8216;test_field&#8217; and one submit button we called &#8217;submit&#8217; and already gave the value &#8216;Send!&#8217; to it. Now once the submit button gets pressed, the data of the input fields will be send using the method POST to the file form_handle.php ( as set in the form tag ). This means all values of the input fields will be stored into $_POST['input_field_name'] variables. So in our case we got 2 input fields, and so 2 $_POST variables will be created. One for the field &#8216;test_field&#8217;, which will be stored in $_POST['test_field'], and one for the submit button field we called &#8217;submit&#8217;, which will bestored in $_POST['submit']. So in this way the data will be send to the page once the form gets submitted using the form. The submit button we gave a default value already &#8216;Send!&#8217; so for this input field always this variable will be created:</p>
<p><pre name="code" class="php:nogutter">
$_POST['submit'] = "Send!";
</pre>
</p>
<p>Once the form has been submitted. So we can actually CHECK if the form was submitted, by validating this:</p>
<p><pre name="code" class="php:nogutter">
&lt;?php
if($_POST['submit'] == "Send!") { //form has been submitted correctly?

   //handle form data

}

  //show form

}
?>
</pre>
<p>Because when the form gets submitted, as mentioned above, for each field will be created a variable $_POST['field_name'] and given a value ( either filled in by user or the default value ) which is default set to &#8216;Send!&#8217; for the submit button. So the variable $_POST['submit'] must have been created if the form was submitted and must be given the value &#8216;Send!&#8217; to as we gave it that value inside the form submit button input field. But we also made another input field we called &#8216;test&#8217;. This field we didn&#8217;t gave a value and can be filled in by the user as it&#8217;s a &#8220;text&#8221; input field. Which looks like this:</p>
<p></p>
<input type="text" name="test">
<p></p>
<p>And we want to show what the user filled in there. And as we know the data of the input fields are stored in $_POST['input_field_name'], we can get the data filled in for the field named &#8216;test&#8217; from the variable $_POST['test']. So let&#8217;s do this. But of course only when the form was submitted this is possible, so we use the loop we created to check whether the form was submitted or not:</p>
<p><strong>File: form_handle.php</strong></p>
<pre name="code" class="php:nogutter">
&lt;?php

if($_POST['submit'] == "Send!") { //form has been submitted correctly?

   //handle form data
   echo "<b>Input field: 'test'</b> - You filled in: ".$_POST['test'];

}else{ //not submitted? show form

?>

&lt;form method="POST" action="fom_handle.php">
 &lt;input type="text" name="test_field">
 &lt;input type="submit" name="submit" value="Send!">
&lt;/form>

&lt;?php

}

?>
</pre>
<p>When the form has not been submitted yet, this will output:</p>
<p></p>
<form method="POST" action="fom_handle.php">
<input type="text" name="test_field">
<input type="submit" name="submit" value="Send!">
</form>
<p></p>
<p>Once the form has been submitted this will output:</p>
<p> </p>
<p><b>Input field: &#8216;test&#8217;</b> &#8211; You filled in: [here what the user filled in for this field]</p>
<p>Allright, so those are the basics of retrieving user input data. The same principe works for all other input fields such as checkboxes ( which get their value when they&#8217;re checked ), radio boxes, etc..</p>
<p>However there&#8217;s also a second method: the GET method. It works the same for retrieving the data, they&#8217;re put inside $_GET['input_field_name'] when submitting the form. However, they can be changed inside the url. As they&#8217;re now submited through url. Like:</p>
<blockquote><p>
form_handle.php?submit=Send!&#038;test=what_the_user_filled_in_for_this_field</p></blockquote>
<p>So it could be manipulated very easily by changing that inside the url, and beside that, the user can see all values of as well hidden input fields ( which are given a default value for example ) through url. For example you&#8217;d have an input field:</p>
<pre name="code" class="php:nogutter">
&lt;input type='hidden' name='key' value='myverylongsecretkey2985230'>
</pre>
<p></p>
<p>Then once the form gets submitted using GET method you&#8217;ll see this key just in the url!</p>
<blockquote><p>form_handle.php?key=myverylongsecretkey2985230</p></blockquote>
<p>So you don&#8217;t want that. So usually POST methods are used for securely submitting form, user input data.</p>
<p><h3>End of tutorial</h3>
</p>
<p>We&#8217;ve come to the end of this small tutorial. Hope you learnt something in this tutorial and also have a look at the tutorial about <a href="http://www.webcodez.net/php-mysql/user-input-validation/">User Input Validation</a>. Which can nicely be combined with this tutorial on how to actually first RETRIEVE the user input data before validating it or anything. Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/retrieving-user-input-data/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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>
		<item>
		<title>Basic Login System</title>
		<link>http://www.webcodez.net/php-mysql/basic-login-system/</link>
		<comments>http://www.webcodez.net/php-mysql/basic-login-system/#comments</comments>
		<pubDate>Wed, 20 Jan 2010 14:53:57 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[arrays]]></category>
		<category><![CDATA[basics]]></category>
		<category><![CDATA[if loop]]></category>
		<category><![CDATA[Login System]]></category>
		<category><![CDATA[MySql]]></category>
		<category><![CDATA[net script]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[php login]]></category>
		<category><![CDATA[php simple]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[variables]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=177</guid>
		<description><![CDATA[In the previous tutorial we&#8217;ve been making a register system. In this tutorial we&#8217;ll be creating a login system for it, where members can login to your website and for example get access to a members area of your website. We&#8217;ll basicly be using SESSION variables in this tutorial to save the login session of [...]]]></description>
			<content:encoded><![CDATA[<p>In the previous tutorial we&#8217;ve been making a register system. In this tutorial we&#8217;ll be creating a login system for it, where members can login to your website and for example get access to a members area of your website. We&#8217;ll basicly be using SESSION variables in this tutorial to save the login session of a member but you could also change all sessions into cookies.</p>
<p>Again we start with a form:</p>
<pre name="code" class="php:nogutter">
<form method="POST" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>">

... form login fields ...
</form>
</pre>
<p>The form method we use is the same as for the register system: POST. We use the same page to handle the login attempt so we make it go to ( action ) $_SERVER['PHP_SELF'] which equals the current page/file. So all user data will be send into $_POST['field_name'] variables to the same page ( itself ).</p>
<p>Now we&#8217;ll add the form fields, which for the login system are just the username and password fields and a submit button.</p>
<pre name="code" class="php:nogutter">
<form method="POST" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>">
<input type='text' name='username'>
<input type='password' name='password'>
<input type='submit' name='submit' value='log me in!'>
</form>
</pre>
<p>So once the user submits the form by clicking the submit button, the $_POST array will be created containing:</p>
<p>$_POST['username'] which equals the username filled in<br />
$_POST['password'] which equals the password filled in<br />
($_POST['submit'] which equals &#8216;log me in!&#8217;)</p>
<p>As we&#8217;re going to make it handle the login in the same page, we&#8217;ll need to make an if loop. This if loop will check if the form has been submitted already ( does $_POST exist? ). If so, it will handle the user filled in data which is stored in this $_POST array as explained above. If not, it will show the form as the user has not submitted it yet.</p>
<pre name="code" class="php:nogutter">
 &lt;?php

 if($_POST) {

 ... handle the login attempt ...

 }else{

 ... show the form ...

 }

 ?>
 </pre>
<p>We can already fill in the form in the else part of the loop ( when $_POST does not exist yet ).</p>
<pre name="code" class="php:nogutter">
&lt;?php

if($_POST) {

... handle the login attempt ...

}else{

?>
<form method="POST" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>">
<input type='text' name='username'>
<input type='password' name='password'>
<input type='submit' name='submit' value='log me in!'></form>

&lt;?php

}

?>
</pre>
<p>We nicely seperate the HTML code from the PHP code by first closing the php tag ( ?> ) and then re-opening it after the HTML code ( &lt;?php ) when the php code goes on. Do this rather than echoing the whole form.</p>
<p>Move on to the part of the if loop that occurs when the user did submit the form. First we need to make it connect to the database. We&#8217;ll take as example the database and table we created in the register system tutorial.</p>
<pre name="code" class="php:nogutter">
mysql_connect('localhost', 'root'); //like: 'host','user','pasword'
mysql_select_db('test'); //'database'
</pre>
<p> Let&#8217;s check whether there the login was valid. To do this we use a mysql_query and a mysql function. We assume there&#8217;s a table called &#8216;accounts&#8217; with the fields id, username, password. It could be called anyhow as long as you&#8217;ve created it correctly in the database as well. Have a look at the query first:</p>
<pre name="code" class="php:nogutter">
"SELECT id FROM accounts WHERE username = '".$_POST['username']."' AND password = '".$_POST['password']."' "
</pre>
<p>What it simply does ( well, tries to do ) is select a row ( to be exact the field &#8216;id&#8217;, doesn&#8217;t really matter what field though ) from the table &#8216;accounts&#8217; that has the same value for the field &#8216;username&#8217; and &#8216;password&#8217; as the user filled in ( $_POST['username'] and $_POST['password'] ). In other words: it tries to select an account with the same username and password the user filled in. We&#8217;ll put it into a variable and make it a query using the mysql_query function. Also we&#8217;ll use mysql_real_escape_string again to secure the user input.</p>
<pre name="code" class="php:nogutter">
$check_account = mysql_query("SELECT id FROM accounts WHERE username = '".mysql_real_escape_string($_POST['username'])."' AND password = '".mysql_real_escape_string($_POST['password'])."' ");
</pre>
<p>Now we aren&#8217;t going to actually retrieve the data the mysql query returned ( we aren&#8217;t even sure if the account actually exists ). We&#8217;ll instead use mysql_num_rows to check if there was any row returned by the query.</p>
<pre name="code" class="php:nogutter">
$check_account = mysql_query("SELECT id FROM accounts WHERE username = '".mysql_real_escape_string($_POST['username'])."' AND password = '".mysql_real_escape_string($_POST['password'])."' ");

$check_account1 = mysql_num_rows($check_account);
 </pre>
<p>$check_account1 now contains a number indicating the amount of rows it found with the query. When it found any rows ( so when $check_account1 contains a number greater than 0 ) the account exists. It found a row that has the same username and password as the user filled in. If not: there wasn&#8217;t any row ( any account in this case ) with the same username and password as the user filled in. So we can just make another if loop which checks if the account exists ( $check_account > 0 ).</p>
<pre name="code" class="php:nogutter">
 $check_account = mysql_query("SELECT id FROM accounts WHERE username = '".mysql_real_escape_string($_POST['username'])."' AND password = '".mysql_real_escape_string($_POST['password'])."' ");

$check_account1 = mysql_num_rows($check_account);

if ( $check_account > 0 ) {

    echo "Logged in!"; //account exists, show logged in message

}else{

   echo "Invalid login."; //account doesn't exist, show error message

}
</pre>
<p>Great, now it checks whether an account with the user filled in data exists. But we also want it to remember the user&#8217;s login, in a session. We&#8217;ll make it create a session called &#8216;logged&#8217; to do that.</p>
<pre name="code" class="php:nogutter">
$_SESSION['logged'] = true;
</pre>
<p>Which contains a boolean value indicating the user is logged in. Though this isn&#8217;t enough, we also need to make a session that contains the username or userid of the user logged in. I prefer using the user&#8217;s ID to determine what account is logged in as each user account has its own unique ID.<br />
To get the user account&#8217;s ID, we&#8217;ll use our previous query which actually selected it. However we first used it only to check if it existed. We&#8217;ll now actually retrieve the data ( user id ) of the query using the mysql_fetch_assoc function. We don&#8217;t need to use a while loop because we know it should be only 1 account that the query selects.</p>
<pre name="code" class="php:nogutter">
 $user = mysql_fetch_assoc($check_account); //get the row data the query returned
  $userid = $user['id']; //get the value of the field 'id' of the row the query returned
$_SESSION['userid'] = $userid; //put it into a session
</pre>
<p>And we created all our sessions required to make a user loggin! Let&#8217;s put it all together now.<br />
<strong><br />
File: login.php</strong></p>
<pre name="code" class="php:nogutter">
 &lt;?php

session_start(); // <-- always on top! needed to use our session

 if($_POST) {

 $check_account = mysql_query("SELECT id FROM accounts WHERE username = '".mysql_real_escape_string($_POST['username'])."' AND password = '".mysql_real_escape_string($_POST['password'])."' ");

 $check_account1 = mysql_num_rows($check_account);

if ( $check_account > 0 ) {

    echo "Logged in!"; //account exists, show logged in message

   $user = mysql_fetch_assoc($check_account); //get the row data the query returned

   $userid = $user['id']; //get the value of the field 'id' of the row the query returned

   $_SESSION['userid'] = $userid; //put it into a session

}else{

   echo "Invalid login."; //account doesn't exist, show error message

}

 }else{

 ?>
<form method="POST" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>">
<input type='text' name='username'>
<input type='password' name='password'>
<input type='submit' name='submit' value='log me in!'></form>

 &lt;?php

 }

 ?>
 </pre>
<p>Holdon, you might have noticed we did not use the session_start function yet, so we wouldn&#8217;t be able to use our sessions! Added it on the top of the page ( always! ).</p>
<p>Now the basic login page is done. We&#8217;ve now come to the part of &#8216;how to use the login?&#8217;. Well, we know that if a user is logged in, a session called &#8216;logged&#8217; is created and set to true ( ALWAYS, for all users that log in ). So we simply check if this session was created and equal to true, to check if a user is logged in:<br />
<strong><br />
file: sample_members_area.php</strong></p>
<pre name="code" class="php:nogutter">
&lt;?php
session_start(); //<--- there it is again

if($_SESSION['logged'] == true) {

    echo "Welcome user!";

}else{

   include("login.php"); //include the login page

}

?>
</pre>
<p>You could also add this to the login page. Also needed is to use the user id to get all info of the user. To do this we can use another mysql SELECT query just like we done to get the user id, but now for the username, password, email or any other field.</p>
<pre name="code" class="php:nogutter">
"SELECT username FROM accounts WHERE id = '".$_SESSION['userid']."' "
</pre>
<p>We now for example select the username of the user account with the id stored in the session &#8216;userid&#8217;, which equals the id of the user logged in.So it selects the username of the logged in user.We can again retrieve the data using mysql_fetch_assoc. Also remember to put the query into the mysql_query function to execute it.</p>
<pre name="code" class="php:nogutter">
$username = mysql_query("SELECT username FROM accounts WHERE id = '".$_SESSION['userid']."' ");

$username = mysql_fetch_assoc($username);

$username = $username['username']; //yeah bit weird names chosen, I know
</pre>
<p>So you could greet the user with:</p>
<pre name="code" class="php:nogutter">
echo "Hi there ".$username."! &lt;br /> Long time no see!";
</pre>
<p>End results:</p>
<p><strong>File: Login.php</strong></p>
<pre name="code" class="php:nogutter">
  &lt;?php

session_start(); // <-- always on top! needed to use our session

if($_SESSION['logged'] == true) { //user already logged in?

   include("Members_area.php"); //include members area

}else{

  if($_POST) {

  $check_account = mysql_query("SELECT id FROM accounts WHERE username = '".mysql_real_escape_string($_POST['username'])."' AND password = '".mysql_real_escape_string($_POST['password'])."' ");

  $check_account1 = mysql_num_rows($check_account);

 if ( $check_account > 0 ) {

     echo "Logged in!"; //account exists, show logged in message

   $user = mysql_fetch_assoc($check_account); //get the row data the query returned

   $userid = $user['id']; //get the value of the field 'id' of the row the query returned

   $_SESSION['userid'] = $userid; //put it into a session

 }else{

    echo "Invalid login."; //account doesn't exist, show error message

 }

  }else{

  ?>
<form method="POST" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>">
<input type='text' name='username'>
<input type='password' name='password'>
<input type='submit' name='submit' value='log me in!'></form>

  &lt;?php

  }

}

  ?>
  </pre>
<p><strong>File: Members_area.php</strong></p>
<pre name="code" class="php:nogutter">
&lt;?php
session_start(); //<--- there it is again

if($_SESSION['logged'] == true) {

    $username = mysql_query("SELECT username FROM accounts WHERE id = '".$_SESSION['userid']."' ");

    $username = mysql_fetch_assoc($username);

    $username = $username['username']; //yeah bit weird names chosen, I know

    echo "Hi there ".$username."! &lt;br /> Long time no see!";

}else{

   include("login.php"); //include the login page

}

?>
</pre>
<p>Cheers,<br />
Admin.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/basic-login-system/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Basic Register System</title>
		<link>http://www.webcodez.net/php-mysql/basic-register-system/</link>
		<comments>http://www.webcodez.net/php-mysql/basic-register-system/#comments</comments>
		<pubDate>Wed, 20 Jan 2010 14:41:48 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[arrays]]></category>
		<category><![CDATA[basics]]></category>
		<category><![CDATA[if loop]]></category>
		<category><![CDATA[MySql]]></category>
		<category><![CDATA[net script]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[php register]]></category>
		<category><![CDATA[php simple]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[register system]]></category>
		<category><![CDATA[variables]]></category>
		<category><![CDATA[while loop]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=161</guid>
		<description><![CDATA[In this tutorial we&#8217;ll be creating a register system in which people can create their own account. It&#8217;s a basic register system which uses some mysql functions to insert data into the database (create the account), loops and some PHP functions to handle the POST variables. We&#8217;ll start creating our register page with a form [...]]]></description>
			<content:encoded><![CDATA[<p>In this tutorial we&#8217;ll be creating a register system in which people can create their own account. It&#8217;s a basic register system which uses some mysql functions to insert data into the database (create the account), loops and some PHP functions to handle the POST variables. We&#8217;ll start creating our register page with a form in which the user can fill in the info for his or her account.</p>
<p><strong>File: Register.php</strong></p>
<pre name="code" class="html:nogutter">&lt;form method="POST" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>">

... form felds ...

&lt;/form></pre>
<p>We start by creating the form itself. The attributes we set are method and action. Method is used to define how the data (text filled in the form fields) should be transferred. We use the POST method, which will store all data filled in by the user into $_POST variables. The action is set to the page where it should go to when the form is submitted. We set it to $_SERVER['PHP_SELF'], which is equal to the current file. So after the user completes filling in our form fields and submits the form, it will put all filled in data into $_POST variables and send it to itself (go to the same page).</p>
<p>Let&#8217;s add some form fields to the form, which the user needs to fill in to complete the registration.</p>
<pre name="code" class="html:nogutter">&lt;form method="POST" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>">

<b>*Username:</b>
<input type='text' name='username'> &lt;br />

<b>*Password  :</b>
<input type='password' name='password'> &lt;br />

<b>*Repeat Password: </b>
<input type='password' name='password_rep'> &lt;br />

<b>*Email:</b>
<input type='text' name='email'> &lt;br />
<input type='submit' name='submit' value='create account'>

&lt;/form></pre>
<p>We simply added 4 fields using basic HTML input tags and a submit button to submit the form. These four fields need to be filled in by the user in order to create his/her account. They may not be left empty: the username, password and email. We also created a &#8220;repeat password&#8221; field, which we use to verify the user filled in password. The name we give each input field is important because for each input field, a POST variable will be created once the user submits the form. The POST variable created for a certain field is $_POST['field_name'] and will contain the value the user gave to that field (filled in for that field). In this way all values of the fields will be submitted using POST variables. We will use these variables to check if the user filled in all fields (if they aren&#8217;t empty) and if the form has been submitted at all.</p>
<p>To actually create the account we&#8217;ll be storing the filled in values for the fields, into a database. Let&#8217;s create a database called &#8220;test&#8221; and a table called &#8220;accounts&#8221; which contains 4 fields ( equal to the amount of fields that are filled in for the form plus one ID field which is unique for each member ( password and repeat password should contain one and the same value so are of course just stored in one field: password ) ). If you are not sure how to do this you could also import the SQL code :</p>
<pre name="code" class="php:nogutter">SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
CREATE DATABASE 'test' DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE 'test';
CREATE TABLE IF NOT EXISTS 'accounts' (
  'id' int(250) NOT NULL AUTO_INCREMENT,
  'username' varchar(20) NOT NULL,
  'password' varchar(20) NOT NULL,
  'email' varchar(50) NOT NULL,
  PRIMARY KEY ('id')
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;</pre>
<p>Now we&#8217;ll create a loop to check if the user has already submitted the form. Which is the case when all fields data have been stored into $_POST variables. In other words: if the $_POST variables exist – the form has been submitted. This doesn&#8217;t mean all fields have been filled in though, because the $_POST variables could also be empty, but they are created ( as the user submitted the form).</p>
<pre name="code" class="php:nogutter">&lt;?php

If ( ... the form has been submitted ... ) {

    ... check if all fields have been filled in correctly ...

}else{ //form has not been submitted yet

    ... show the form ...

}

?>
</pre>
<p>This is how our loop looks like. Now we can already fill in our form which we just created and to check if the form has been submitted we just check if $_POST variable exists:</p>
<pre name="code" class="php:nogutter">
&lt;?php
If ( $_POST  ) {

    ... check if all fields have been filled in correctly - create account if valid ...

}else{ //form has not been submitted yet

?>

&lt;form method="POST" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>">

<b>*Username:</b>
<input type='text' name='username'> &lt;br />

<b>*Password  :</b>
<input type='password' name='password'> &lt;br />

<b>*Repeat Password: </b>
<input type='password' name='password_rep'> &lt;br />

<b>*Email:</b>
<input type='text' name='email'> &lt;p>
<input type='submit' name='submit' value='create account'>

&lt;/form>

&lt;?php

}

?></pre>
<p>Only thing last is to check all fields and create the account if valid. As mentioned before, once the form has been submitted, all field values have been stored into $_POST['field_name']. So to check if all fields have been filled in, we just need to check if all $_POST variables aren&#8217;t empty. To do this we are going to use a foreach loop to make it easier. We could also just check all $_POST variables like: $_POST['username'] and $_POST['password'], etc.. But this is an inefficient way to do it, as when you add a new form field, you would need to add it to the loop as well ( check that field too ). Beside that it just can be done much easier and faster than checking all fields manually. The foreach loop will check all fields and values the same way. Let&#8217;s just have alook at the loop code:</p>
<pre name="code" class="php:nogutter">foreach ( $_POST as $key => $value ) {

    if ( empty($value) )

        $errors .= "Field '".$key."' has to be filled in. &lt;br /> ";

    }else{

        ... check if filled in values are valid ...

    }

}</pre>
<p>Ok, let&#8217;s go through this code. What it basicly does is check all sub-variables of the array $_POST ( which are all fields ) and store the name of them in $key and the value of them in $value. As for each field a sub-variable for the array $_POST has been created, it will check each field. $key will contain the name of the field and $value the value ( filled in by the user ). Then we use an if loop to check if the value of the field is empty: we use the function empty to do this. If it&#8217;s empty, we&#8217;ll add text to a variable called $errors. This variable we use to store all errors into if any. This way we can also check if there are any errors at all by checking if the variable $errors contains anything: if not, the user filled in all fields correctly and we can create the account. Otherwise it should show the errors ( echo $errors ).</p>
<p>Now there&#8217;s one more part of the if loop that needs to be done: the part where it checks if the values filled in are actually valid. This part runs when the $value was not empty. We&#8217;ll use a function preg_match for this. What we basicly do is check if it contains the characters that are allowed ( which are basicly: numbers, spaces and alphabetical characters ). The function works like this:</p>
<pre name="code" class="php:nogutter">preg_match("/[...pattern that needs to be matched...]/", $value_to_check)</pre>
<p>In our case the pattern is equal to all numbers, spaces and alphabetical characters as mentioned above. The value to check is the filled in value of the field, which is stored in $value as as well mentioned above. This makes us end up with the following code:</p>
<pre name="code" class="php:nogutter">        If ( !preg_match("/[0-9A-Za-z -_]/", $value) )
            $errors .= "&lt;p> Field '".$key."' has been given an invalid value. &lt;/p>";</pre>
<p>All numbers are 0-9, all capital alphabetical characters are A-Z and all normal alphabetical characters are a-z, and we also allow the &#8211; and _ symbols to be used. Now we check if the value filled in for the current field ( stored in $value ) does NOT match this pattern . Which is the case when it contains any other symbols/characters than the ones given in the pattern. We use the ! symbol for that, which means simply: NOT. In that case we add an error to the $error variable ( the field is not filled in correctly, using inappropriate characters ).</p>
<p>Let&#8217;s put it all together.</p>
<pre name="code" class="php:nogutter">&lt;?php

If ( $_POST  ) {

foreach ( $_POST as $key => $value ) {

        if ( empty($value) )

            $errors .= "&lt;p> Field '".$key."' has to be filled in. &lt;/p>";

        }else{

            If ( !preg_match("/[0-9A-Za-z -_]/", $value) )
                $errors .= "&lt;p> Field '".$key."' has been given an invalid value. &lt;/p>";

        }

}

    ...  check if the passwords ( normal and repeated ) matched ...

    ... check if username/email does not already exist ...

    ...  check if there were any errors with the filled in fields ...

}else{ //form has not been submitted yet

?>

&lt;form method="POST" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>">

<b>*Username:</b>
<input type='text' name='username'> &lt;br />

<b>*Password  :</b>
<input type='password' name='password'> &lt;br />

<b>*Repeat Password: </b>
<input type='password' name='password_rep'> &lt;br />

<b>*Email:</b>
<input type='text' name='email'> &lt;p>
<input type='submit' name='submit' value='create account'>

&lt;/form>

&lt;?php

}

?></pre>
<p>There&#8217;s one field that needs to be checked in a different way: the &#8216;password_rep&#8217; field. Which needs to be equal to the password field. We&#8217;ll use another if loop for that (already put into the code above):</p>
<pre name="code" class="php:nogutter">        If( $_POST['password_rep'] != $_POST['password'])
            $errors .= "&lt;p> Passwords don't match! &lt;/p>";</pre>
<p>A simple condition checks whether they are not equal to eachother (!=). In that case, an error will be added.</p>
<p>Now there&#8217;s a last thing that needs to be checked. We&#8217;re going to check if there isn&#8217;t already an account on the given username or email. We&#8217;ll use a simple mysql SELECT query to do this:</p>
<pre name="code" class="php:nogutter">        $check_account = mysql_query("SELECT id
                                                                    FROM accounts
                                                                    WHERE username = '".$_POST['username']."' OR email = '".$_POST['email']."' ");</pre>
<p>We select the field &#8216;id&#8217; from the table &#8216;accounts&#8217; (we could select any field) from a row where the username or email is equal to what the user filled in as username/email. To make it more secure we can use the mysql_real_escape_string function that escapes all possible harming characters out of the strings.</p>
<pre name="code" class="php:nogutter">        $check_account = mysql_query("SELECT id
                                                                     FROM accounts
                                                                     WHERE username = '".mysql_real_escape_string($_POST['username'])."' OR email = '".mysql_real_escape_string($_POST['email'])."' ");</pre>
<p>Next, instead of retrieving the rows/results ( as we aren&#8217;t sure if there is any row like this already ) we&#8217;ll check if the query selected any rows at all. In other words: we&#8217;ll check if there is already an account with this username or email as this is the only thing we need to check with this query. We&#8217;ll use the function mysql_num_rows to do this.</p>
<pre name="code" class="php:nogutter">        $check_account = mysql_query("SELECT id
                                                                    FROM accounts
                                                                    WHERE username = '".mysql_real_escape_string($_POST['username'])."' OR email = '".mysql_real_escape_string($_POST['email'])."' ");

        $check_account = mysql_num_rows($check_account);</pre>
<p>$check_account now contains a number of the rows that have the same username or email as the user filled in for his account to register. So if $check_account contains a number greater than 0, this means there&#8217;s already 1 or more accounts with this username or email. In that case an error should be added that the username or email already exists for an account.</p>
<pre name="code" class="php:nogutter">        $check_account = mysql_query("SELECT id
                                                                    FROM accounts
                                                                    WHERE username = '".mysql_real_escape_string($_POST['username'])."' OR email = '".mysql_real_escape_string($_POST['email'])."' ");

        $check_account = mysql_num_rows($check_account);

        If($check_account > 0)
            $errors .= "&lt;p> An account with the same username or email already exists. &lt;/p>";</pre>
<p>Now we need to create a code to check if there were any errors: in other words if $errors contains text. We&#8217;ll again use the empty function. If $errors is empty, we can create the account. Otherwise we show the errors.</p>
<p>Now we checked all possible errors for the user filled in data for his/her account to be created. So let&#8217;s put it all together.</p>
<pre name="code" class="php:nogutter">&lt;?php

If ( $_POST  ) {

foreach ( $_POST as $key => $value ) {

        if ( empty($value) )

            $errors .= "&lt;p> Field '".$key."' has to be filled in. &lt;/p>";

        }else{

            If ( !preg_match("/[0-9A-Za-z -_]/", $value) )
                $errors .= "&lt;p> Field '".$key."' has been given an invalid value. &lt;/p>";

        }

}
        If( $_POST['password_rep'] != $_POST['password'])
            $errors .= "&lt;p> Passwords don't match! &lt;/p>";

        $check_account = mysql_query("SELECT id FROM accounts WHERE username = '".mysql_real_escape_string($_POST['username'])."' OR email = '".mysql_real_escape_string($_POST['email'])."' ");

        $check_account = mysql_num_rows($check_account);

        If($check_account > 0)
            $errors .= "&lt;p> An account with the same username or email already exists. &lt;/p>";

    ...  check if there were any errors with the filled in fields ...

}else{ //form has not been submitted yet

?>

&lt;form method="POST" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>">

<b>*Username:</b>
<input type='text' name='username'> &lt;br />

<b>*Password  :</b>
<input type='password' name='password'> &lt;br />

<b>*Repeat Password: </b>
<input type='password' name='password_rep'> &lt;br />

<b>*Email:</b>
<input type='text' name='email'> &lt;p>
<input type='submit' name='submit' value='create account'>

&lt;/form>

&lt;?php

}

?></pre>
<pre name="code" class="php:nogutter">If ( empty($errors) OR !isset($errors) ) {

    ... create account ...

}else{

    ... show errors ...

}</pre>
<p>Showing the errors is not such a big deal, we just echo the variable $errors which contains all errors. Creating the account isn&#8217;t such a big deal either. We&#8217;ll be using a few mysql functions &#038; queries. Which we use to insert rows into the database ( create the account ). First we&#8217;ll need to connect to the host and database. We&#8217;ll use the functions mysql_connect and mysql_select_database.</p>
<pre name="code" class="php:nogutter">mysql_connect("host", "user", "pass");
mysql_select_db("database");</pre>
<p>We&#8217;ll now use a basic mysql_query function to INSERT the values into the database.</p>
<pre name="code" class="php:nogutter">mysql_query( ... query ... );</pre>
<p>In our case the query is to INSERT all values into the table &#8216;accounts&#8217;.</p>
<pre name="code" class="php:nogutter">$query = mysql_query("INSERT INTO accounts(username, password, email)VALUES('".$_POST['username']."', '".$_POST['password']."', '".$_POST['email']."')");</pre>
<p>That&#8217;s how the query looks like. I think it isn&#8217;t that hard so will explain it shortly: we use INSERT INTO to insert data into a table, in our case &#8216;account&#8217;s . Then we need to define which fields we want to insert data into, and put them between brackets after the table: username, password, email in this case. Also we need to give the VALUES for each field, which are stored in $_POST['field_name']. Though, to be sure there won&#8217;t be any SQL injections possible, we will still use the mysql_real_escape_string function to handle all filled in values so that they can&#8217;t harm the database with any bad codes. Even though we already checked the values, you should never just directly insert user filled in data to the database.</p>
<pre name="code" class="php:nogutter">$query = mysql_query("INSERT INTO accounts(username, password, email)VALUES('".mysql_real_escape_string($_POST['username'])."', '".mysql_real_escape_string($_POST['password'])."', '".mysql_real_escape_string($_POST['email'])."')");</pre>
<p>Now we need to check if the query was successfully:</p>
<pre name="code" class="php:nogutter">If($query) {

    echo "Success! Account created!";

}else{

    echo "There was an error creating the account. Please try again or contact the web administrator";

}</pre>
<p>We just use a basic loop to check if the $query variable, which executes the mysql query, was executed successfully.</p>
<p>Now we put it all together!<br />
 <br />
<strong>File: Register.php</strong></p>
<pre name="code" class="php:nogutter">&lt;?php

If ( $_POST  ) {

foreach ( $_POST as $key => $value ) {

        if ( empty($value) )

            $errors .= "&lt;p> Field '".$key."' has to be filled in. &lt;/p>";

        }else{

            If ( !preg_match("/[0-9A-Za-z -_]/", $value) )
                $errors .= "&lt;p> Field '".$key."' has been given an invalid value. &lt;/p>";

        }

    }

        If( $_POST['password_rep'] != $_POST['password'])
            $errors .= "&lt;p> Passwords don't match! &lt;/p>";

        $check_account = mysql_query("SELECT id FROM accounts WHERE username = '".mysql_real_escape_string($_POST['username'])."' OR email = '".mysql_real_escape_string($_POST['email'])."' ");

        $check_account = mysql_num_rows($check_account);

        If($check_account > 0)
            $errors .= "&lt;p> An account with the same username or email already exists. &lt;/p>";

If ( empty($errors) OR !isset($errors) ) {

mysql_connect(host, user, pass);
mysql_select_db(database);

$query = mysql_query("INSERT INTO accounts(username, password, email)VALUES('".mysql_real_escape_string($_POST['username'])."', '".mysql_real_escape_string($_POST['password'])."', '".mysql_real_escape_string($_POST['email'])."')");

If($query) {

    echo "Success! Account created!";

}else{

    echo "There was an error creating the account. Please try again or contact the web administrator";

}

}else{

    echo $errors;

}

}else{ //form has not been submitted yet

?>

&lt;form method="POST" action="&lt;?php echo $_SERVER['PHP_SELF']; ?>">

<b>*Username:</b>
<input type='text' name='username'> &lt;br />

<b>*Password  :</b>
<input type='password' name='password'> &lt;br />

<b>*Repeat Password: </b>
<input type='password' name='password_rep'> &lt;br />

<b>*Email:</b>
<input type='text' name='email'> &lt;p>
<input type='submit' name='submit' value='create account'>

&lt;/form>

&lt;?php

}

?></pre>
<p>And we&#8217;ve got our register system in ONE file!</p>
<p>Note: In queries you might have seen a lot of quotes and double quotes. We use &#8216;&#8221;. and .&#8221;&#8216; to separate an array ( like $_POST[] ) from the rest of the query.</p>
<p>Cheers,<br />
Admin.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/basic-register-system/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>POST Variables</title>
		<link>http://www.webcodez.net/php-mysql/post-variables/</link>
		<comments>http://www.webcodez.net/php-mysql/post-variables/#comments</comments>
		<pubDate>Sun, 17 Jan 2010 15:05:06 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[arrays]]></category>
		<category><![CDATA[basics]]></category>
		<category><![CDATA[fundamentals]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[variables]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=124</guid>
		<description><![CDATA[When you create forms, you can either use the POST or GET method. In this chapter I&#8217;ll be explaining the POST method, in which the data is put into POST variables. POST variables are just like normal arrays which contain a certain amount of (sub-)variables. Once a form is submitted, for each form field one [...]]]></description>
			<content:encoded><![CDATA[<p>When you create forms, you can either use the <strong>POST </strong>or GET method. In this chapter I&#8217;ll be explaining the <strong>POST </strong>method, in which the data is put into POST variables. POST variables are just like normal arrays which contain a certain amount of (sub-)variables. Once a form is submitted, for each form field one sub-variable will be created for the array POST, the name of the sub-variable (index) will be equal to the name of the field. The value of the sub-variable will be equal to the value of the form field ( what the user filled in or the default value otherwise, if set ). So let&#8217;s start with creating a form that uses this POST method.</p>
<p><strong>Example:</strong></p>
<pre name="code" class="html:nogutter">
<form method="POST" action="handle_file.php">
... form fields ...
</form>
</pre>
<p>We simply put <strong>method=&#8221;POST&#8221; </strong>to the form tag, to make it use this method. The action here is set to some “handle_file.php&#8221;, could as well be set to any file or even the same file. It&#8217;s the file it will send the data ( using the POST method, in POST variables so ) to and go to when the form is submitted. Let&#8217;s add an example form field and submit button.</p>
<p><strong>Example:</strong></p>
<pre name="code" class="html:nogutter">
<form method="POST" action="handle_file.php">
<input type="text" name="username">
<input type="submit" name="submit" value="Post!">
</form>
</pre>
<p>In this case, once the user submits the form by clicking on the submit button, the text filled in in the field ‘username&#8217; ( the first input field with name=&#8217;username&#8217; ), will be put into the variable $_POST[‘username']. The same goes for all input fields. All values of the input fields will be stored into a variable $_POST[‘field_name_here'] and sent to the action file. Let&#8217;s use this to greet the user when he fills in his username and submits it:<br />
<strong><br />
File: form.php</strong></p>
<pre name="code" class="html:nogutter">
<form method="POST" action="handle_file.php">
<input type="text" name="username">
<input type="submit" name="submit" value="Post!">
</form>
</pre>
<p><strong>File: handle_file.php</strong></p>
<pre name="code" class="php:nogutter">&lt;?php
if(!empty($_POST['username']))
    echo "Hi there ".$_POST['username']."!";
 ?></pre>
<p>What we basicly done here is check if the field username is not empty, as the value of it would be stored into $_POST[‘username'] once the form has been submitted. So we actually check 2 things by checking whether it&#8217;s not empty. We check if the form has been submitted at all, and we check whether the input field with the name username has not been left blank. Then we use the value of it ( the username the user filled in ) to greet the user with a simple greeting.<br />
That&#8217;s it, if you have any further questions about this chapter ( POST variables ), feel free to ask.</p>
<p>Cheers,<br />
Admin.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/post-variables/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
