<?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>Team Tutorials&#187; Using jQuery to Reorder a List and Update a Database</title>
	<atom:link href="http://teamtutorials.com/category/web-development-tutorials/php-tutorials/feed" rel="self" type="application/rss+xml" />
	<link>http://teamtutorials.com</link>
	<description></description>
	<lastBuildDate>Fri, 23 Jul 2010 12:13:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Using jQuery to Reorder a List and Update a Database</title>
		<link>http://teamtutorials.com/web-development-tutorials/using-jquery-to-reorder-a-list-and-update-a-database</link>
		<comments>http://teamtutorials.com/web-development-tutorials/using-jquery-to-reorder-a-list-and-update-a-database#comments</comments>
		<pubDate>Wed, 30 Sep 2009 21:05:23 +0000</pubDate>
		<dc:creator>John Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[PHP Tutorials]]></category>
		<category><![CDATA[Web Development Tutorials]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Reorder]]></category>
		<guid isPermaLink="false">http://teamtutorials.com/?p=2126</guid>
		<description><![CDATA[This tutorial will show you how to use jQuery to allow as list (UL) to be reordered and will also make an AJAX call to a PHP file that will update the database when an item is dropped. I found this useful for a project I was working on recently. The user wanted to be able to change the order that categories displayed in a report. The items are stored in a database with a field called display_order. When the report is generated we simply order by that field.]]></description>
			<content:encoded><![CDATA[<p>This tutorial will show you how to use jQuery to allow as list (UL) to be reordered and will also make an AJAX call to a PHP file that will update the database when an item is dropped. I found this useful for a project I was working on recently. The user wanted to be able to change the order that categories displayed in a report. The items are stored in a database with a field called display_order. When the report is generated we simply order by that field.</p>
<p><strong>This tutorial requires:</strong></p>
<ul>
<li>A web server that handles PHP and MySql or <a href="http://teamtutorials.com/web-development-tutorials/setting-up-a-wamp-server">setup a local  Windows Apache MySql Php web server.</a></li>
<li> <a href="http://jqueryui.com/download"> jQuery and jQuery UI</a>.
<li>Basic HTML/CSS/Javascript knowledge.</li>
</ul>
<p>First you are going to need to <a href="http://jqueryui.com/download" target=="blank">download jQuery Ui.</a> There are plenty of feature within jQuery User Interface that I will not be touching in this tutorial, but for sake of the tutorial download the entire bundle. Also I will be using the default (UI Lightness) theme.<br />
Create a folder for this project on your server. You will need to unzip the jQuery files and put them all in this directory.<br />
<a href="http://teamtutorials.com/wp-content/uploads/2009/09/jquery-reorder-tutorial-01.gif"><img src="http://teamtutorials.com/wp-content/uploads/2009/09/jquery-reorder-tutorial-01.gif" alt="jquery-reorder-tutorial-01" title="jquery-reorder-tutorial-01" width="700" height="417" class="alignnone size-full wp-image-2129" /></a></p>
<p>Since jQuery comes with an example called index.html I am going to name my file test.php. You can call it whatever you want. Create the file. We will use it later. We&#8217;ll set the database up first.</p>
<p>I like to use <a href=" http://www.heidisql.com/" target="blank">HeidiSQL</a> when working with MySQL. Now on the database server I am going to create a database call test_tutorials, with a table called report_items. Here are the field properties for the report_items table:<br />
<a href="http://teamtutorials.com/wp-content/uploads/2009/09/jquery-reorder-tutorial-02.gif"><img src="http://teamtutorials.com/wp-content/uploads/2009/09/jquery-reorder-tutorial-02.gif" alt="jquery-reorder-tutorial-02" title="jquery-reorder-tutorial-02" width="624" height="159" class="alignnone size-full wp-image-2130" /></a></p>
<p>Now populate your table with some test data. I&#8217;ll insert 6 rows. Also make sure you insert the display order starting from 0.<br />
<a href="http://teamtutorials.com/wp-content/uploads/2009/09/jquery-reorder-tutorial-03.jpg"><img src="http://teamtutorials.com/wp-content/uploads/2009/09/jquery-reorder-tutorial-03.jpg" alt="jquery-reorder-tutorial-03" title="jquery-reorder-tutorial-03" width="576" height="235" class="alignnone size-full wp-image-2131" /></a></p>
<p>You can save the changes to your data base and get back to working on test.php. Open the file. We&#8217;ll start with the basic layout. </p>
<pre class="brush: xml;">
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
&lt;title&gt;Reorder Test&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Next we&#8217;ll include the stylesheet from our jQuery theme. I&#8217;ll also add some CSS from the example on the jQuery UI website. Then we&#8217;ll include the jQuery javascript files.</p>
<pre class="brush: xml;">
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
&lt;title&gt;Reorder Test&lt;/title&gt;
&lt;/head&gt;
&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;development-bundle/themes/base/ui.all.css&quot;/&gt;
&lt;style type=&quot;text/css&quot;&gt;
	#sortable {
		list-style-type: none;
		margin: 0;
		padding: 0;
		width: 60%;
	}
	#sortable li {
		margin: 0 3px 3px 3px;
		padding: 0.4em;
		padding-left: 1.5em;
		font-size: 1.4em;
		height: 18px;
	}
	#sortable li span {
		position: absolute;
		margin-left: -1.3em;
	}
&lt;/style&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery-1.3.2.min.js&quot;&gt; &lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery-ui-1.7.2.custom.min.js&quot;&gt;&lt;/script&gt;
&lt;body&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>We are going to pull the intial data from the database. In order to do this we&#8217;ll need to make a database connection. Create a new file called connect.php and create a database connection (obvious added your credentials where needed.</p>
<pre class="brush: php;">
&lt;?php
$servername='localhost'; //no need to change if the file is located on the same server
$dbusername='username'; //your db username
$dbpassword='password'; //your db password
$dbname='database'; //for this tutorial I called my db test_tutorials
connecttodb($servername,$dbname,$dbusername,$dbpassword);
function connecttodb($servername,$dbname,$dbuser,$dbpassword){
	global $link;
	$link=mysql_connect ($servername,$dbuser,$dbpassword);
	if(!$link){die(&quot;Could not connect to MySQL&quot;);}
	mysql_select_db($dbname,$link) or die (&quot;could not open db&quot;.mysql_error());
}
?&gt;
</pre>
<p>Save connect.php and include it into your test.php file:</p>
<pre class="brush: php;">
&lt;?php include('connect.php');?&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
&lt;title&gt;Reorder Test&lt;/title&gt;
&lt;/head&gt;
&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;development-bundle/themes/base/ui.all.css&quot;/&gt;
&lt;style type=&quot;text/css&quot;&gt;
	#sortable {
		list-style-type: none;
		margin: 0;
		padding: 0;
		width: 60%;
	}
	#sortable li {
		margin: 0 3px 3px 3px;
		padding: 0.4em;
		padding-left: 1.5em;
		font-size: 1.4em;
		height: 18px;
	}
	#sortable li span {
		position: absolute;
		margin-left: -1.3em;
	}
&lt;/style&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery-1.3.2.min.js&quot;&gt; &lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery-ui-1.7.2.custom.min.js&quot;&gt;&lt;/script&gt;
&lt;body&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Now we need to retrieve the database results and dsiplay them. The items will be display in an un-ordered list. We&#8217;ll add this code to the body.</p>
<pre class="brush: php;">
&lt;body&gt;
	&lt;ul id=&quot;sortable&quot;&gt;
    &lt;?php
	$sql = &quot;select * from report_items order by Category_Display_Order ASC&quot;;
	$query = mysql_query($sql);
	while($row = mysql_fetch_array($query))
	{
		$catid = $row['Category_ID'];
		$catname = $row['Category_Name'];
		echo &quot;&lt;li id='item_$catid' class='ui-state-default'&gt;&lt;span class='ui-icon ui-icon-arrowthick-2-n-s'&gt;&lt;/span&gt;$catname&lt;/li&gt;&quot;;
	}
	?&gt;
    &lt;/ul&gt;
&lt;/body&gt; </pre>
<p>Take not above. When we echo the li we are adding the ui-state-default class which is just a jQuery theme class and the span that we included is an arrow icon also provide with jQuery Ui. Where you see item_$catid, that should be your primary key from your database (this will be used later to reorder items.</p>
<p>Now save the file and load it in your browser. If you followed everything hopefully you will get something like this:<br />
<a href="http://teamtutorials.com/wp-content/uploads/2009/09/jquery-reorder-tutorial-04.jpg"><img src="http://teamtutorials.com/wp-content/uploads/2009/09/jquery-reorder-tutorial-04.jpg" alt="jquery-reorder-tutorial-04" title="jquery-reorder-tutorial-04" width="700" height="183" class="alignnone size-full wp-image-2132" /></a></p>
<p>Now we&#8217;ll enable the sortable function on our list. Remeber I gave the UL tag an id of sortable. Add this code in the head below your jquery javascript files:</p>
<pre class="brush: jscript;">
&lt;script type=&quot;text/javascript&quot;&gt;
	$(function() {
		$(&quot;#sortable&quot;).sortable({
			placeholder: 'ui-state-highlight',
		});
		$(&quot;#sortable&quot;).disableSelection();
	});
&lt;/script&gt;
</pre>
<p>The code above enables sorting of the UL with the id #sortable. The placeholder: &#8216;ui-state-highlight&#8217; tells jquery we want it to show a place holder of where we can drop the item. In the them I am using it is a yellow box. Make the changes above and save your page. You should now be able to drap and drop your list items.<br />
<a href="http://teamtutorials.com/wp-content/uploads/2009/09/jquery-reorder-tutorial-05.jpg"><img src="http://teamtutorials.com/wp-content/uploads/2009/09/jquery-reorder-tutorial-05.jpg" alt="jquery-reorder-tutorial-05" title="jquery-reorder-tutorial-05" width="700" height="206" class="alignnone size-full wp-image-2133" /></a></p>
<p>Now that you have that working we can move to the AJAX call. When an item is dropped, we want to call a php file to update the database. We do that by using the stop: action. So when dragging stops, the script will call the url (updatedb.php) we provided below. To make the AJAZ called, we let jQuery do the work.</p>
<pre class="brush: jscript;">
&lt;script type=&quot;text/javascript&quot;&gt;
	$(function() {
		$(&quot;#sortable&quot;).sortable({
			placeholder: 'ui-state-highlight',
			stop: function(i) {
				placeholder: 'ui-state-highlight'
				$.ajax({
					type: &quot;GET&quot;,
					url: &quot;updatedb.php&quot;,
					data: $(&quot;#sortable&quot;).sortable(&quot;serialize&quot;)});
			}
		});
		$(&quot;#sortable&quot;).disableSelection();
	});
&lt;/script&gt;
</pre>
<p>You see the ajax function above. We tell it what type of request, in this case wer&#8217;ll use get variables. We also tell it what URL, this is a php file we&#8217;ll create to update the database. Then we add the data that will be sent. </p>
<p>The code $(&#8220;#sortable&#8221;).sortable(&#8220;serialize&#8221;)}); will take the items within our ordered list and serialize it. It will take the items of the list, in whatever order they are in, and turn them into a get variable. So for each item it will add it to an array and format is properly to make the call to the PHP file. The data will look like this:<br />
item[]=1&#038;item[]=2&#038;item[]=3&#038;item[]=4&#038;item[]=5&#038;item[]=6</p>
<p>If you want to debug AJAX request I recommend  using Firefox with the Firebug plugin. If you want to see that the request is being attempted and that what the data looks like, you can add an alert box just below the placeholder like this: alert($(&#8220;#sortable&#8221;).sortable(&#8220;serialize&#8221;));<br />
Save the changes to you file we are done with test.php. Here is my full source of test.php up to this point.</p>
<pre class="brush: plain;">
&lt;?php include('connect.php');?&gt;
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
&lt;title&gt;Reorder Test&lt;/title&gt;
&lt;/head&gt;
&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;development-bundle/themes/base/ui.all.css&quot;/&gt;
&lt;style type=&quot;text/css&quot;&gt;
	#sortable {
		list-style-type: none;
		margin: 0;
		padding: 0;
		width: 60%;
	}
	#sortable li {
		margin: 0 3px 3px 3px;
		padding: 0.4em;
		padding-left: 1.5em;
		font-size: 1.4em;
		height: 18px;
	}
	#sortable li span {
		position: absolute;
		margin-left: -1.3em;
	}
&lt;/style&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery-1.3.2.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery-ui-1.7.2.custom.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
	$(function() {
		$(&quot;#sortable&quot;).sortable({
			placeholder: 'ui-state-highlight',
			stop: function(i) {
				placeholder: 'ui-state-highlight'
				$.ajax({
					type: &quot;GET&quot;,
					url: &quot;updatedb.php&quot;,
					data: $(&quot;#sortable&quot;).sortable(&quot;serialize&quot;)});
			}
		});
		$(&quot;#sortable&quot;).disableSelection();
	});
&lt;/script&gt;
&lt;body&gt;
	&lt;ul id=&quot;sortable&quot;&gt;
    &lt;?php
	$sql = &quot;select * from report_items order by Category_Display_Order ASC&quot;;
	$query = mysql_query($sql);
	while($row = mysql_fetch_array($query))
	{
		$catid = $row['Category_ID'];
		$catname = $row['Category_Name'];
		echo &quot;&lt;li id='item_$catid' class='ui-state-default'&gt;&lt;span class='ui-icon ui-icon-arrowthick-2-n-s'&gt;&lt;/span&gt;$catname&lt;/li&gt;&quot;;
	}
	?&gt;
    &lt;/ul&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Now we need to actually update the database. Create a file called updatedb.php. This file is pretty simple. We take each item in the array and then update the database based on the array position($key) and the primary key ($value)</p>
<pre class="brush: php;">
&lt;?php
include('connect.php');
foreach($_GET['item'] as $key=&gt;$value) {
	mysql_query(&quot;UPDATE report_items SET Category_Display_Order = '$key' WHERE Categoryt_ID ='$value';&quot;);
}
?&gt; </pre>
<p>Save that file and test the reorder. If you have problems and you think it is with the AJAX call. Check fire bug. Here is an example of a bad request in this case I tried to include a file that was not there.<br />
<a href="http://teamtutorials.com/wp-content/uploads/2009/09/jquery-reorder-tutorial-06.jpg"><img src="http://teamtutorials.com/wp-content/uploads/2009/09/jquery-reorder-tutorial-06.jpg" alt="jquery-reorder-tutorial-06" title="jquery-reorder-tutorial-06" width="700" height="277" class="alignnone size-full wp-image-2134" /></a></p>
<p><strong>I hope this tutorial helped someone out</strong></p>
<ul>
<li><a href="http://demos.teamtutorials.com/jquery_reoder_list/list_tutorial.rar">Download Source</a></li>
<li><a href="http://demos.teamtutorials.com/jquery_reoder_list/">View Live Demo (no database interaction)</a></li>
</ul>
<h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://teamtutorials.com/web-development-tutorials/simple-php-website-templates" title="Simple PHP Website Templates">Simple PHP Website Templates</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/hide-and-show-a-div-using-javascript" title="Hide and Show a Div Using Javascript">Hide and Show a Div Using Javascript</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/installing-code-editor" title="Installing Code Editor">Installing Code Editor</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/how-to-return-mysql-results-to-a-table" title="How to Return MySQL Results to a Table">How to Return MySQL Results to a Table</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/creating-checkboxes-based-on-sql-results" title="Creating Checkboxes Based on SQL Results">Creating Checkboxes Based on SQL Results</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://teamtutorials.com/web-development-tutorials/using-jquery-to-reorder-a-list-and-update-a-database/feed</wfw:commentRss>
		<slash:comments>27</slash:comments>
		</item>
		<item>
		<title>Sending E-Mail to validate User Sign-up</title>
		<link>http://teamtutorials.com/web-development-tutorials/sending-e-mail-to-validate-user-sign-up</link>
		<comments>http://teamtutorials.com/web-development-tutorials/sending-e-mail-to-validate-user-sign-up#comments</comments>
		<pubDate>Thu, 23 Jul 2009 01:06:51 +0000</pubDate>
		<dc:creator>Mike Maguire</dc:creator>
				<category><![CDATA[PHP Tutorials]]></category>
		<category><![CDATA[Web Development Tutorials]]></category>
		<category><![CDATA[email validation]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[web]]></category>
		<guid isPermaLink="false">http://teamtutorials.com/?p=1996</guid>
		<description><![CDATA[In on of our last tutorials we covered how to <a href="http://teamtutorials.com/web-development-tutorials/validating-email-address-with-php-and-ajax">verify that a user’s email address is formatted correctly</a> as well as verify that it goes to a valid domain name. That is great, but still not a great way to make sure a user actually owns or uses that e-mail address. This tutorial will walk you through one method of sending the user an e-mail upon signing up that gives them a link to activate their account.]]></description>
			<content:encoded><![CDATA[<p>In one of our last tutorials we covered how to <a href="http://teamtutorials.com/web-development-tutorials/validating-email-address-with-php-and-ajax">verify that a user’s email address is formatted correctly</a> as well as verify that it goes to a valid domain name. That is great, but still not a great way to make sure a user actually owns or uses that e-mail address. This tutorial will walk you through one method of sending the user an e-mail upon signing up that gives them a link to activate their account. This will require them to click on the link in the e-mail before they can actually login to the site. Let’s get started. First, let’s create a table to hold our user information. I made a database called teamtutorials on my local server and ran this to create the table.</p>
<pre class="brush: sql;">
CREATE TABLE `users` (
  `user_id` int(7) unsigned NOT NULL auto_increment,
  `display_name` varchar(20) NOT NULL,
  `password` varchar(255) NOT NULL,
  `first_name` varchar(25) NOT NULL,
  `last_name` varchar(25) NOT NULL,
  `email_address` varchar(255) NOT NULL,
  PRIMARY KEY  (`user_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=0;
</pre>
<p>Now that the table is set up and configured the way we need it to be we can start creating the php files. We will start with the simple form file. This is adduser.php (it doesn’t have to be a php file but I do it so that If I add something later that is php it is already a php file.)</p>
<pre class="brush: xml;">
&lt;form method=&quot;post&quot; action=&quot;register.php&quot; name=&quot;createuser&quot;&gt;
	UserName:&lt;input type=&quot;text&quot; name=&quot;display_name&quot; id=&quot;display_name&quot;/&gt;&lt;br /&gt;
	First Name:&lt;input type=&quot;text&quot; name=&quot;fname&quot; id=&quot;name&quot;/&gt;&lt;br /&gt;
	Last Name:&lt;input type=&quot;text&quot; name=&quot;lname&quot; id=&quot;surname&quot;/&gt;&lt;br /&gt;
	E-mail:&lt;input type=&quot;text&quot; name=&quot;email&quot; id=&quot;email&quot;/&gt;&lt;br /&gt;
	Password:&lt;input type=&quot;password&quot; name=&quot;pass&quot; id=&quot;pass&quot;/&gt;&lt;br /&gt;
	Confirm PW:&lt;input type=&quot;password&quot; name=&quot;pass2&quot; id=&quot;pass2&quot;/&gt;&lt;br /&gt;
	&lt;input type=&quot;submit&quot; value=&quot;Sign Me Up!&quot;/&gt;
&lt;/form&gt;
</pre>
<p>Next, we will need to create the register.php file that will be called when the form is submitted. </p>
<pre class="brush: php;">
&lt;?php
if ((!isset($_POST['display_name']))||(!isset($_POST['fname']))||(!isset($_POST['lname']))||(!isset($_POST['email']))||(!isset($_POST['pass']))){
		header('Location: http://www.teamtutorials.com');
	}
</pre>
<p>First, we start the php tag and then check for the POST variables to be set. If any of them are not set it will send them back to the creation form.</p>
<pre class="brush: php;">
else
	{
		$servername='localhost';
		$dbusername='dbusername';
		$dbpassword='dbpassword';
		$dbname='full db name';
		global $link;
		$link=mysql_connect ($servername,$dbuser,$dbpassword);
		if(!$link){die(&quot;Could not connect to MySQL&quot;);}
		mysql_select_db($dbname,$link) or die (&quot;could not open db&quot;.mysql_error());
</pre>
<p>If all of the POST variables are set we continue by setting the server variables and creating the database connection. Ensure that you change the variables to your server access information.</p>
<pre class="brush: php;">
		$display_name = $_POST['display_name'];
		$password = $_POST['pass'];
		$first_name = $_POST['fname'];
		$last_name = $_POST['lname'];
		$email_address = $_POST['email'];
		$sha_password = sha1($password);
		$hash_string = hash('md5',$display_name);
</pre>
<p>This just stores all the values into variables that are easier to work with so we don’t have to call the POST global every time. We sha1 the password because it is not reversible so it makes it the most secure. The hash_string is a md5 hash value of the display_name so that it isn’t easily readable. We use the display name because it will be unique and specific to the user. </p>
<pre class="brush: php;">
$query = &quot;insert into `users` values(Null,'$display_name','$sha_password','$first_name','$last_name','$email_address',0,1,CURRENT_TIMESTAMP,Null,'$company_name',8);&quot;;
		mysql_query($query) or die (&quot;Error in query: $query &quot; . mysql_error());
		$user_id = mysql_insert_id();
</pre>
<p>Next, we insert a row into our table that we made using the variables that were passed from the form. We also get the ID of the inserted row so we know what the user id will be.</p>
<pre class="brush: php;">
		$headers = &quot;From: activations@teamtutorials.com \r\n&quot;;
		$validate_link = &quot;http://teamtutorials.com/validate.php?id=$user_id&amp;string=$hash_string&quot;;
		$email_body = &quot;Thank-you for signing up on TeamTutorials. Click on the link below to complete your registration. If you have any issues completing the verfication please let us know. \n\n $validate_link \n\n TeamTutorials Staff&quot;;
</pre>
<p>This builds all the information needed to generate an e-mail using php. The headers sets the from field so that the email will be from a user (if you don’t set this it will be nobody (the user which apache runs under in linux). The validate link is a link to the file that will validate the user when they click on it. The \n command is the php new line command.</p>
<pre class="brush: php;">
		if (mail($email_address,&quot;TeamTutorials Sign-Up&quot;,$email_body,$headers)){
			echo &quot;Email has been sent to &quot;.$email_address.&quot;. Please check your e-mail for steps to activate your account. Check your spam folder as sometimes these 		e-mail get marked as spam. If you still do not see your e-mail, please &lt;a href='http://teamtutorials.com/sendemail.php?function=validation&amp;id=$user_id'&gt; Click Here&lt;/a&gt; to resend.&quot;;
		}
		else
		{
			echo &quot;There was an error sending an e-mail to your e-mail address. Please contact us to let us know of the issue.&quot;;
		}
	}
?&gt;
</pre>
<p>Finally we attempt to send the e-mail and echo success or failure. That concludes this file. Finally we need to make the file that will validate the user when they click on the link in the e-mail that we just sent them. This file is validate.php.</p>
<pre class="brush: php;">
&lt;?php
if (isset($_GET['id']))&amp;&amp;(isset($_GET['id'])){
	$id = $_GET['id'];
	$hashstring = $_GET['string'];
	$storedhashvalue = &quot;&quot;;
</pre>
<p>First we make sure the values are in the url that we are expecting. At the end of the file we will re-direct them to the home page if these values aren’t set.</p>
<pre class="brush: php;">
$query = &quot;select user_id,display_name from `users` where user_id=$id;&quot;;
	$result = mysql_query($query) or die (&quot;Error in query: $query &quot; . mysql_error());
	$row = mysql_fetch_assoc($result);
	$storedhashvalue = hash('md5',$row['display_name']);
	mysql_free_result($result);
</pre>
<p>These lines run a query against the table to get the information for the user based on the user id in the url. It then re-hashes the value so that we can compare the on in the url to match.</p>
<pre class="brush: php;">
	if ($storedhashvalue == $hashstring){
		$query = &quot;update `users` set active_flag=1 where user_id=$id;&quot;;
		$result = mysql_query($query) or die (&quot;Error in query: $query &quot; . mysql_error());
		echo &quot;Your account has been activated. Please &lt;a href='http://teamtutorials.com/login.php&gt;Click Here To Login&lt;/a&gt;&quot;;
	}
	else
	{
		echo &quot;Your account could not be verified. Please verify that the link has not been modified from the e-mail. If it still does not work, please contact us.&quot;;
	}
</pre>
<p>If the values match we update the database to see the user as active and if it doesn’t work we tell them that it failed. </p>
<pre class="brush: php;">
}
else
{
header('Location: http://www.teamtutorials.com');
}
?&gt;
</pre>
<p>Finally we re-direct the user if the variables are not in the url. Now if you go to adduser.php and fill out the form and hit submit. It will send whatever e-mail you put in the form an e-mail with a link in it. Click on the link to activate the user. That concludes this tutorial. If you have any questions, please leave it in the comments. Thanks for viewing.</p>
<h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://teamtutorials.com/web-development-tutorials/php-tutorials/creating-a-form-that-will-search-a-mysql-database" title="Creating a Form that will Search a MySQL Database">Creating a Form that will Search a MySQL Database</a></li><li><a href="http://teamtutorials.com/windows-tutorials/downloading-and-installing-heidi-sql" title="Downloading and Installing Heidi SQL">Downloading and Installing Heidi SQL</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/using-jquery-to-reorder-a-list-and-update-a-database" title="Using jQuery to Reorder a List and Update a Database">Using jQuery to Reorder a List and Update a Database</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/how-to-parse-a-csv-file-using-php" title="How to Parse a CSV File Using PHP">How to Parse a CSV File Using PHP</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/how-to-return-mysql-results-to-a-table" title="How to Return MySQL Results to a Table">How to Return MySQL Results to a Table</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://teamtutorials.com/web-development-tutorials/sending-e-mail-to-validate-user-sign-up/feed</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>How to Parse a CSV File Using PHP</title>
		<link>http://teamtutorials.com/web-development-tutorials/how-to-parse-a-csv-file-using-php</link>
		<comments>http://teamtutorials.com/web-development-tutorials/how-to-parse-a-csv-file-using-php#comments</comments>
		<pubDate>Thu, 18 Jun 2009 22:07:06 +0000</pubDate>
		<dc:creator>John Ward</dc:creator>
				<category><![CDATA[PHP Tutorials]]></category>
		<category><![CDATA[Web Development Tutorials]]></category>
		<category><![CDATA[comma separated value. fgetcsv]]></category>
		<category><![CDATA[csv]]></category>
		<category><![CDATA[fopen]]></category>
		<category><![CDATA[parse]]></category>
		<category><![CDATA[php]]></category>
		<guid isPermaLink="false">http://teamtutorials.com/?p=1850</guid>
		<description><![CDATA[In this tutorial you will learn a simple way to parse CSV files using PHP and output the text of the fields you need. This tutorial is not going to go into what you can do with the data once you get it from the CSV as the possibilities are endless. We will simply show you how to get the data into an array in PHP.]]></description>
			<content:encoded><![CDATA[<p>In this tutorial you will learn a simple way to parse CSV files using PHP and output the text of the fields you need. This tutorial is not going to go into what you can do with the data once you get it from the CSV as the possibilities are endless. We will simply show you how to get the data into an array in PHP.</p>
<p><a href="http://teamtutorials.com/wp-content/uploads/2009/06/test.csv"><br />
First you can download our test.csv file here. </a></p>
<p>Now we are going to open the file for reading using the fopen() function in PHP. Will will specify the location of the file and also the mode in which we want to open it. In this case we are using the &#8220;R&#8221; mode which stands for read. Other possible uses of this function can be found on the <a href="http://us2.php.net/manual/en/function.fopen.php">manual page for fopen()</a>.</p>
<pre class="brush: php;">
&lt;?php
$handle = fopen(&quot;test.csv&quot;, &quot;r&quot;);
?&gt;
</pre>
<p>Next we are going to create a while loop. We will use this loop to parse each line of the CSV.</p>
<pre class="brush: php;">
&lt;?php
$handle = fopen(&quot;test.csv&quot;, &quot;r&quot;);
while () {
}
?&gt;
</pre>
<p>Next we are going to use the <a href="http://us3.php.net/manual/en/function.fgetcsv.php">fgetcsv() function </a>to &#8220;split&#8221; each line of our CSV file into an array called $data. When there are no lines left the condition will be false and will end the loop. In the fgetcsv() function we will pass the file handle, length (optional) and the separating character (which is a comma in this case.<br />
test</p>
<pre class="brush: php;">
&lt;?php
$handle = fopen(&quot;test.csv&quot;, &quot;r&quot;);
while (($data = fgetcsv($handle, 5000, &quot;,&quot;)) !== FALSE) {
}
?&gt;
</pre>
<p>*note: If you data fields are encapsulated using a character such as &#8211; (for ease of example) you can specify the enclosure filed like so: fgetcsv($handle, 5000, &#8220;,&#8221;,&#8221;-&#8221;). By default the enclosure character is a double quote, but the function will also handle no enclosure character.</p>
<p>Next all we have to do is echo the fields that we want to see. We will use the field number in the array to do this. I will echo the second value in the CSV.</p>
<pre class="brush: php;">
&lt;?php
$handle = fopen(&quot;test.csv&quot;, &quot;r&quot;);
$row = 1;
while (($data = fgetcsv($handle, 5000, &quot;,&quot;)) !== FALSE) {
	echo $data[2];
	echo &quot;&lt;/br&gt;&quot;;
}
?&gt;
</pre>
<p>Another note. If you do not know which value the field you are looking for will be in the array just print the array like this:</p>
<pre class="brush: php;">
&lt;?php
$handle = fopen(&quot;test.csv&quot;, &quot;r&quot;);
while (($data = fgetcsv($handle, 5000, &quot;,&quot;)) !== FALSE) {
	echo &quot;&lt;pre&gt;&quot;;
	print_r($data);
	echo &quot;&lt;pre&gt;&quot;;
}
?&gt;
</pre>
<p>As you can see it is pretty simple to parse csv using this method. You may have issue with memory if you try to open large files using fopen. in that case you will want to read the file line-by-line, but that is another tutorial.</p>
<h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://teamtutorials.com/web-development-tutorials/using-jquery-to-reorder-a-list-and-update-a-database" title="Using jQuery to Reorder a List and Update a Database">Using jQuery to Reorder a List and Update a Database</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/sending-e-mail-to-validate-user-sign-up" title="Sending E-Mail to validate User Sign-up">Sending E-Mail to validate User Sign-up</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/how-to-return-mysql-results-to-a-table" title="How to Return MySQL Results to a Table">How to Return MySQL Results to a Table</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/editing-mysql-data-using-php" title="Editing MySQL Data Using PHP">Editing MySQL Data Using PHP</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/how-to-get-a-users-geo-location" title="How to Get a Users Geo Location?">How to Get a Users Geo Location?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://teamtutorials.com/web-development-tutorials/how-to-parse-a-csv-file-using-php/feed</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Validating Email Address with PHP and AJAX</title>
		<link>http://teamtutorials.com/web-development-tutorials/validating-email-address-with-php-and-ajax</link>
		<comments>http://teamtutorials.com/web-development-tutorials/validating-email-address-with-php-and-ajax#comments</comments>
		<pubDate>Mon, 08 Jun 2009 07:05:27 +0000</pubDate>
		<dc:creator>Mike Maguire</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[HTML Tutorials]]></category>
		<category><![CDATA[JavaScriptTutorials]]></category>
		<category><![CDATA[PHP Tutorials]]></category>
		<category><![CDATA[Web Development Tutorials]]></category>
		<guid isPermaLink="false">http://teamtutorials.com/?p=1837</guid>
		<description><![CDATA[This tutorial will walk you through checking for an e-mail to be valid as the user is filling out the form without having to reload the page.]]></description>
			<content:encoded><![CDATA[<p>This tutorial will walk you through checking for an e-mail to be valid as the user is filling out the form without having to reload the page. Bear in mind, that there is no way to make sure that we get an accurate working e-mail every time. All we can do is prevent users from using extremely random ones or for domains that don’t exist. I was working on a form for a new website that is going to require users to create an account and was browsing the web to see what people use to validate e-mails, other than the obvious choice of running it through a reg-ex (regular expression), and I came across a site that showed me a feature of php that can be useful. The original post can be found over at <a href="http://davidwalsh.name/php-email-validator-mx-dns-record-check">David Walsh’s website</a>. I think that using that this php function as well as a reg-ex and running them from an AJAX call should do the trick. So let’s get started. You can get the images we will be using <a href="http://teamtutorials.com/files/email_validation_images.zip">here. </a>First we will make the form that will call the functions. Since this will be our user account creator we’ll call it adduser.php. (I’m leaving out the default HTML/CSS as you can do that however you like – you may also note that this file could be an HTML as there is no php in this section  – this is just a part of the much larger file that I am working with (-:). </p>
<pre class="brush: xml;">
&lt;script type=&quot;text/javascript&quot; src=&quot;includes/js/validate_email.js&quot;&gt;&lt;/script&gt;
&lt;form method=&quot;post&quot; action=&quot;register.php&quot; name=&quot;user&quot;&gt;
&lt;h2&gt;User Creation&lt;/h2&gt;
UserName (Display Name):&lt;input type=&quot;text&quot; name=&quot;display_name&quot; id=&quot;display_name&quot;/&gt; &lt;br /&gt;
First Name:&lt;input type=&quot;text&quot; name=&quot;fname&quot; id=&quot;name&quot;/&gt;&lt;br /&gt;
Last Name:&lt;input type=&quot;text&quot; name=&quot;lname&quot; id=&quot;surname&quot;/&gt;&lt;br /&gt;
E-mail:&lt;input type=&quot;text&quot; name=&quot;email&quot; id=&quot;email&quot; onBlur=&quot;checkEmail()&quot;/&gt;&lt;div id=&quot;emailflag&quot; style=&quot;display:inline;&quot;&gt;&lt;img src=&quot;images/failure.gif&quot;&gt;&lt;/div&gt;&lt;br /&gt;
Password:&lt;input type=&quot;password&quot; name=&quot;pass&quot; id=&quot;pass&quot;/&gt;
Confirm PW:&lt;input type=&quot;password&quot; name=&quot;pass2&quot; id=&quot;pass2&quot; /&gt;
&lt;br  /&gt;
&lt;/form&gt;
</pre>
<p>Only a few things to note here: the onBlur command in the e-mail textbox is the first. This is going to call the email function (which is included in the script include at the beginning of the file) every time that textbox is tabbed or clicked away from. Also, note the div after the textbox, that contains the failure image now as we will use that ID to change the image later. Next, we need to create the php file that will actually do the validation when the AJAX calls it. Let’s call this file validate_email.php. I’ll break this one down a little to explain what’s going on. </p>
<pre class="brush: php;">
&lt;?php
if (isset($_GET['email'])){
	isValidEmail($_GET['email']);
}
</pre>
<p>This couple of lines simply checks for a variable to be set and if it is, calls the function to validate the address – this will prevent from someone going straight to this file or going to it with a blank string. As you can see we pass the value in the variable to the function. </p>
<pre class="brush: php;">
function isValidEmail($email)
	{
	$myReg=&quot;/^[A-Za-z0-9\._-]+@[A-Za-z0-9_-]+\.([A-Za-z0-9_-][A-Za-z0-9_]+)$/&quot;;
		if(preg_match($myReg, $email)){
			if(domain_exists($_GET['email']))
			{
				echo(&quot;&lt;img src=\&quot;images/success.gif\&quot;&gt;&quot;);
			}
			else
			{
				echo(&quot;&lt;img src=\&quot;images/failure.gif\&quot;&gt;&quot;);
			}
		}
		else
		{
			echo(&quot;&lt;img src=\&quot;images/failure.gif\&quot;&gt;&quot;);
		}
	}
</pre>
<p>The function looks worse than it actually is due to the reg-ex. They can be a little confusing, but once you understand what it does, it’s not that bad….but that is another tutorial. For now just know it checks the string that is passed to it to be formatted correctly. First we set the reg-ex and then we pass the address to it through the preg_match command. This will process the string to match the reg-ex and output true or false. If it passes validation, we then pass it to our function to check the MX record. If that passes we echo the path to success.gif (which is a green check-mark), otherwise we echo the path to failure.gif (which is a red x). Note that for these to work you will need to put the images in the proper locations or change the path to the images. Finally, in this file we need to create the domain_exists fcuntion that we called in the above section of code. </p>
<pre class="brush: php;">
function domain_exists($email,$record = 'MX')
{
	list($user,$domain) = split('@',$email);
	return checkdnsrr($domain,$record);
}
?&gt;
</pre>
<p>This simply runs the e-mail(after splitting the email at the @ symbol) through the checkdnsrr which checks for the MX record to be retrievable from the domain name. This essentially just checks for a server to be responding at that domain name. Technically we could still put an e-mail that doesn’t exist, as all we check is for the domain to exist. Next, we need to create the AJAX call file. We’ll call this file validate_email.js.</p>
<pre class="brush: jscript;">
function checkEmail(){
	httpObject = getHTTPObject();
	if (httpObject != null) {
		if (!document.getElementById('email').value== &quot;&quot;){
			httpObject.open(&quot;GET&quot;, &quot;../includes/php/validate_email.php?email=&quot;+document.getElementById('email').value, true);
			httpObject.send(null);
			httpObject.onreadystatechange = setImage;
		}
		else
		{
			document.getElementById('emailflag').innerHTML = &quot;&lt;img src=\&quot;images/failure.gif\&quot;&gt;&quot;;
		}
	}
}
</pre>
<p>This file has 3 functions in it. The first one is the function that we are calling from the form in the first file. This function calls the getHTTPObject function to initialize the AJAX call that we will use. Next, we check for the email field in the form to contain information and if it does, we do an HTTP GET request to call the php file and pass it the email that is currently in the textbox. If it contains no data it sets the div that is created right after the textbox to contain the failure image. Once the HTTP object state changes, we call the function that will pass the image contents. </p>
<pre class="brush: jscript;">
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;);
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert(&quot;Your browser does not support AJAX.&quot;);
return null;
}}
</pre>
<p>This function declares the httpObject that we will be using and throws an error in the browser if it does not support the call. </p>
<pre class="brush: jscript;">
function setImage(){
if(httpObject.readyState == 4){
document.getElementById('emailflag').innerHTML = httpObject.responseText;
}}
</pre>
<p>This final function checks for the state of the object to be 4 (completed) and if it is it sets the innerHTML of the ID from the form to whatever was echoed from the PHP file (either the success or the failure gif). That completes the files. Ensure that all the files are in the right place. I have my php file in /includes/php/validate_email.php and the javascript file is /includes/js/validate_email.js. </p>
<p><img src="http://teamtutorials.com/wp-content/uploads/2009/06/ajax_php_email_validation_01.jpg" alt="ajax_php_email_validation_01" title="ajax_php_email_validation_01" width="464" height="177" class="alignnone size-full wp-image-1839" /></p>
<p>This is the form that should be shown when you go to the main form. </p>
<p><img src="http://teamtutorials.com/wp-content/uploads/2009/06/ajax_php_email_validation_02.jpg" alt="ajax_php_email_validation_02" title="ajax_php_email_validation_02" width="471" height="189" class="alignnone size-full wp-image-1840" /></p>
<p>When you type a valid e-mail into the e-mail box, the checkmark should appear where the X was like above.</p>
<p><img src="http://teamtutorials.com/wp-content/uploads/2009/06/ajax_php_email_validation_03.jpg" alt="ajax_php_email_validation_03" title="ajax_php_email_validation_03" width="453" height="184" class="alignnone size-full wp-image-1838" /></p>
<p>If you put in a improperly formatted e-mail like above, it should switch it back to an X. It will also go back to an X if you blank out the text box. </p>
<p>That completes this tutorial. Some of this can be hard to follow so please leave any questions or comments you have in the comments sections and we’ll help you out where we can. Also, I made the reg-ex fit as many things as I could, if you find a valid e-mail that it fails, please let me know so that I can modify it to work. Thanks for viewing this tutorial and I hope it was easy to follow. </p>
<h2  class="related_post_title">Other Related Tutorials</h2><ul class="related_post"><li><a href="http://teamtutorials.com/programming-tutorials/handling-error-to-prevent-application-crashes-in-vb" title="Handling Errors To Prevent Application Crashes in VB">Handling Errors To Prevent Application Crashes in VB</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/replace-wordpress-search-with-google-search-box" title="Replace Wordpress Search With Google Search Box">Replace Wordpress Search With Google Search Box</a></li><li><a href="http://teamtutorials.com/windows-tutorials/disable-visual-effects-to-speed-up-windows-xp" title="Disable Visual Effects to Speed Up Windows XP">Disable Visual Effects to Speed Up Windows XP</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/how-and-why-you-should-still-use-tables" title="How and Why You Should Still Use Tables">How and Why You Should Still Use Tables</a></li><li><a href="http://teamtutorials.com/windows-tutorials/graphically-mapping-the-files-on-your-harddrive" title="Graphically Mapping The Files on Your Harddrive">Graphically Mapping The Files on Your Harddrive</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://teamtutorials.com/web-development-tutorials/validating-email-address-with-php-and-ajax/feed</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>How to Return MySQL Results to a Table</title>
		<link>http://teamtutorials.com/web-development-tutorials/how-to-return-mysql-results-to-a-table</link>
		<comments>http://teamtutorials.com/web-development-tutorials/how-to-return-mysql-results-to-a-table#comments</comments>
		<pubDate>Tue, 31 Mar 2009 00:24:08 +0000</pubDate>
		<dc:creator>John Ward</dc:creator>
				<category><![CDATA[PHP Tutorials]]></category>
		<category><![CDATA[Web Development Tutorials]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[tables]]></category>
		<guid isPermaLink="false">http://teamtutorials.com/?p=1804</guid>
		<description><![CDATA[This question has been asked several times lately and I wanted to clear this up. This is a very easy concept once you get it down. In order to display the results from a MySQL query into a table will will store the results in an array and then echo out each row in a while loop.]]></description>
			<content:encoded><![CDATA[<p>This question has been asked several times lately and I wanted to clear this up. This is a very easy concept once you get it down. In order to display the results from a MySQL query into a table will will store the results in an array and then echo out each row in a while loop.</p>
<p>First off. I am going to use a table that I created in the past tutorials on this site.</p>
<p>The table contains the following fields:</p>
<p>ID &#8211; auto generated integer<br />
FName &#8211; First Name, varchar<br />
LName &#8211; Last Name, varchar<br />
PHON &#8211; Phone number, varchar</p>
<p>Create the table and populate some test data if you haven&#8217;t done so already. If you don&#8217;t know how to do this please visit some of our other MySQL tutorials.</p>
<p>Create your database connection</p>
<pre class="brush: php;">
&lt;?php
//create a database connection
mysql_connect(&amp;quot;localhost&amp;quot;,&amp;quot;your username&amp;quot;,&amp;quot;password&amp;quot;) or die(&amp;quot;Error: &amp;quot;.mysqlerror());
//select your database
mysql_select_db(&amp;quot;your db&amp;quot;);
?&gt;
</pre>
<p>Next we need to setup the table. We will add the column headings.</p>
<pre class="brush: php;">
&lt;?php
//create a database connection
mysql_connect(&amp;quot;localhost&amp;quot;,&amp;quot;your username&amp;quot;,&amp;quot;password&amp;quot;) or die(&amp;quot;Error: &amp;quot;.mysqlerror());
//select your database
mysql_select_db(&amp;quot;your db&amp;quot;);
?&gt;
&lt;html&gt;
&lt;body&gt;
&lt;table border=1&gt;
  &lt;tr&gt;
   &lt;th&gt;ID&lt;/th&gt;
   &lt;th&gt;First Name&lt;/th&gt;
   &lt;th&gt;Last Name&lt;/th&gt;
   &lt;th&gt;Phone Number&lt;/th&gt;
  &lt;/tr&gt;
</pre>
<p>As you can see above we ended our PHP code and create an HTML table. The TR tage is used to defined a table row and the TH tag is used for Table Headings.</p>
<p>In php you can &#8220;break&#8221; out of code and execute HTML and then continue writing php code. Do do this you simply end your php code with then start a new <?php tag when you want to start again.</p>
<p>So the next setup will be to add the php code to select our items from the database.</p>
<pre class="brush: php;">
&lt;?php
//create a database connection
mysql_connect(&amp;quot;localhost&amp;quot;,&amp;quot;your username&amp;quot;,&amp;quot;password&amp;quot;) or die(&amp;quot;Error: &amp;quot;.mysqlerror());
//select your database
mysql_select_db(&amp;quot;your db&amp;quot;);
?&gt;
&lt;html&gt;
&lt;body&gt;
&lt;table border=1&gt;
  &lt;tr&gt;
   &lt;th&gt;ID&lt;/th&gt;
   &lt;th&gt;First Name&lt;/th&gt;
   &lt;th&gt;Last Name&lt;/th&gt;
   &lt;th&gt;Phone Number&lt;/th&gt;
  &lt;/tr&gt;
&lt;?php
//create the query
$query = mysql_query(&amp;quot;select * from `TestTable`&amp;quot;);
//return the array and loop through each row
while ($row = mysql_fetch_array($query)){
	$id = $row['ID'];
	$fname = $row['FName'];
	$lname = $row['LName'];
	$phone = $row['PHON'];
?&gt;
</pre>
<p>Above you will see that we executed a query and returned the results as an array. We will loop through each record and echo the results in the table. Take notice that I DID NOT CLOSE the if statment here on purpose.</p>
<p>Now to we will add the HTML for the rows that are returned. We will use php and echo the results.</p>
<pre class="brush: php;">
&lt;?php
//create a database connection
mysql_connect(&amp;quot;localhost&amp;quot;,&amp;quot;your username&amp;quot;,&amp;quot;password&amp;quot;) or die(&amp;quot;Error: &amp;quot;.mysqlerror());
//select your database
mysql_select_db(&amp;quot;your db&amp;quot;);
?&gt;
&lt;html&gt;
&lt;body&gt;
&lt;table border=1&gt;
  &lt;tr&gt;
   &lt;th&gt;ID&lt;/th&gt;
   &lt;th&gt;First Name&lt;/th&gt;
   &lt;th&gt;Last Name&lt;/th&gt;
   &lt;th&gt;Phone Number&lt;/th&gt;
  &lt;/tr&gt;
&lt;?php
//create the query
$query = mysql_query(&amp;quot;select * from `TestTable`&amp;quot;);
//return the array and loop through each row
while ($row = mysql_fetch_array($query)){
	$id = $row['ID'];
	$fname = $row['FName'];
	$lname = $row['LName'];
	$phone = $row['PHON'];
?&gt;
  &lt;tr&gt;
   &lt;th&gt;&lt;?php echo $id;?&gt;&lt;/th&gt;
   &lt;th&gt;&lt;?php echo $fname;?&gt;&lt;/th&gt;
   &lt;th&gt;&lt;?php echo $lname;?&gt;&lt;/th&gt;
   &lt;th&gt;&lt;?php echo $phone;?&gt;&lt;/th&gt;
  &lt;/tr&gt;
</pre>
<p>Now all we have to do is end the if statement and close all of our open HTML tags.</p>
<pre class="brush: php;">
&lt;?php
//create a database connection
mysql_connect(&amp;quot;localhost&amp;quot;,&amp;quot;your username&amp;quot;,&amp;quot;password&amp;quot;) or die(&amp;quot;Error: &amp;quot;.mysqlerror());
//select your database
mysql_select_db(&amp;quot;your db&amp;quot;);
?&gt;
&lt;html&gt;
&lt;body&gt;
&lt;table border=1&gt;
  &lt;tr&gt;
   &lt;th&gt;ID&lt;/th&gt;
   &lt;th&gt;First Name&lt;/th&gt;
   &lt;th&gt;Last Name&lt;/th&gt;
   &lt;th&gt;Phone Number&lt;/th&gt;
  &lt;/tr&gt;
&lt;?php
//create the query
$query = mysql_query(&amp;quot;select * from `TestTable`&amp;quot;);
//return the array and loop through each row
while ($row = mysql_fetch_array($query)){
	$id = $row['ID'];
	$fname = $row['FName'];
	$lname = $row['LName'];
	$phone = $row['PHON'];
?&gt;
  &lt;tr&gt;
   &lt;th&gt;&lt;?php echo $id;?&gt;&lt;/th&gt;
   &lt;th&gt;&lt;?php echo $fname;?&gt;&lt;/th&gt;
   &lt;th&gt;&lt;?php echo $lname;?&gt;&lt;/th&gt;
   &lt;th&gt;&lt;?php echo $phone;?&gt;&lt;/th&gt;
  &lt;/tr&gt;
&lt;?php } //this ends the if?&gt;
&lt;/table&gt;
&lt;/html&gt;
</pre>
<p>If you do it right you will get something like this:<br />
<img src="http://teamtutorials.com/wp-content/uploads/2009/03/phptable.jpg" alt="Display PHP results in Table" title="Display PHP results in Table" width="303" height="298" class="alignnone size-full wp-image-1805" /></p>
<h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://teamtutorials.com/web-development-tutorials/using-jquery-to-reorder-a-list-and-update-a-database" title="Using jQuery to Reorder a List and Update a Database">Using jQuery to Reorder a List and Update a Database</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/editing-mysql-data-using-php" title="Editing MySQL Data Using PHP">Editing MySQL Data Using PHP</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/creating-checkboxes-based-on-sql-results" title="Creating Checkboxes Based on SQL Results">Creating Checkboxes Based on SQL Results</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/simple-php-website-templates" title="Simple PHP Website Templates">Simple PHP Website Templates</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/php-tutorials/creating-a-form-that-will-search-a-mysql-database" title="Creating a Form that will Search a MySQL Database">Creating a Form that will Search a MySQL Database</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://teamtutorials.com/web-development-tutorials/how-to-return-mysql-results-to-a-table/feed</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Editing MySQL Data Using PHP</title>
		<link>http://teamtutorials.com/web-development-tutorials/editing-mysql-data-using-php</link>
		<comments>http://teamtutorials.com/web-development-tutorials/editing-mysql-data-using-php#comments</comments>
		<pubDate>Fri, 13 Mar 2009 17:01:43 +0000</pubDate>
		<dc:creator>John Ward</dc:creator>
				<category><![CDATA[Database Tutorials]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP Tutorials]]></category>
		<category><![CDATA[Web Development Tutorials]]></category>
		<category><![CDATA[form]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[update]]></category>
		<guid isPermaLink="false">http://teamtutorials.com/?p=1795</guid>
		<description><![CDATA[We have had a few tutorial that show how to display and add data to a MySQL database. Now I am going to show you how to edit a row in your database. In previous examples we setup a table whcih contains: ID, FName, LName and PHON. We will be retreiving the data, making changes, then updating the row in the database. This tutorial is design for the user to update there own information so we will only be editing row for this user.]]></description>
			<content:encoded><![CDATA[<p>We have had a few tutorial that show how to display and add data to a MySQL database. Now I am going to show you how to edit a row in your database. In previous examples we setup a table which contains: ID, FName, LName and PHON. We will be retreiving the data, making changes, then updating the row in the database. This tutorial is designed for the user to update there own information so we will only be editing row for this user. </p>
<p>If you haven&#8217;t taken a look at the past tutorials you may want to:<br />
<a href="http://teamtutorials.com/web-development-tutorials/how-to-access-a-mysql-database-using-php">How to Access a MySQL Database Using PHP</a><br />
<a href="http://teamtutorials.com/web-development-tutorials/php-tutorials/inserting-data-into-a-mysql-database-using-php">Inserting Data Into a MySQL Database using PHP</a></p>
<p>You are going to need to create the database if you haven&#8217;t done so yet. I called my table `TestTable` and populated the following fields:</p>
<p>ID &#8211; Integer, Auto increment<br />
FName &#8211; varchar (first name)<br />
LName &#8211; varchar (last name)<br />
PHON &#8211; varchar (phone number)</p>
<p>Populate some test data into your database and you should be ready to go.</p>
<p>We are going to need to create two files in order to edit the date.<br />
editinfo.php &#8211; We will get the user info from the DB and put it into a form.<br />
updateinfo.php &#8211; We will send the changes from editinfo.php to this for and update the database.</p>
<p>First create editinfo.php</p>
<p>We are going to connect to the database:</p>
<pre class="brush: php;">
&lt;?php
mysql_connect(&quot;localhost&quot;,&quot;USERNAME&quot;,&quot;PASSWORD&quot;) or die(&quot;Error: &quot;.mysql_error()); //add your DB username and password
mysql_select_db(&quot;DBNAME&quot;);//add your dbname
?&gt;
</pre>
<p> Since I am only editing 1 row I am going to just use the user with ID 1. If you were using this in an application you would have this information store when the user is authenticated, but I am going to hard code the user ID into my queries for the example.</p>
<pre class="brush: php;">
&lt;?php
mysql_connect(&quot;localhost&quot;,&quot;USERNAME&quot;,&quot;PASSWORD&quot;) or die(&quot;Error: &quot;.mysql_error()); //add your DB username and password
mysql_select_db(&quot;DBNAME&quot;);//add your dbname
$sql = &quot;select * from `TestTable` where ID = 1&quot;;
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)){
	$id = $row['ID'];
	$fname = $row['FName'];
	$lname = $row['LName'];
	$phone = $row['PHON'];
	//we will echo these into the proper fields
}
mysql_free_result($query);
?&gt;
</pre>
<p>As you can see by the comment about, we will return the rows as an array called $row. Once we build the HTML form we will be able to populate the data into the field. Now I will start with the HTML for the form.</p>
<pre class="brush: xml;">
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Edit User Info&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;form action=&quot;updateinfo.php&quot; method=&quot;post&quot;&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The important things to note in the HTML above is the form action and method. Action is where we will be sending the data. We want to pass all the changes to updateinfo.php and then updateinfo.php will update the database. The method is the method that we will be using to transmit the variables. You can use either GET or POST variables. GET variables will be displayed in the url, for this example we do not want that, we can you the post method.</p>
<p>Next add the form fields. We will use the input tag for this form. Pay attention to the different values if you are not familiar with them. </p>
<p>type=&#8221;text&#8221; &#8211;just means we are using a text field<br />
value=&#8221;" &#8211;this is what the box will display by default.<br />
name=&#8221;id&#8221; &#8211;this is what the variable will be named. This is what we will send to updateinfo.php</p>
<pre class="brush: xml;">
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Edit User Info&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;form action=&quot;updateinfo.php&quot; method=&quot;post&quot;&gt;
userid:&lt;br/&gt;
&lt;input type=&quot;text&quot; value=&quot;&quot; name=&quot;id&quot; disabled/&gt;
&lt;br/&gt;
Last Name:&lt;br/&gt;
&lt;input type=&quot;text&quot; value=&quot;&quot; name=&quot;fname&quot;/&gt;
&lt;br/&gt;
Last Name:&lt;br/&gt;
&lt;input type=&quot;text&quot; value=&quot;&quot; name=&quot;lname&quot;/&gt;
&lt;br/&gt;
Phone Number:&lt;br/&gt;
&lt;input type=&quot;text&quot; value=&quot;&quot; name=&quot;phon&quot;/&gt;
&lt;/br&gt;
&lt;input type=&quot;submit&quot; value=&quot;submit changes&quot;/&gt;
&lt;/form&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Now we have the fields setup. You will notice that the input box for id is disable. This is because I do not want the user to be able to change their ID.</p>
<p>Next step is to populate the form with some data. We will echo the values that we set above in the PHP code.</p>
<pre class="brush: xml;">
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Edit User Info&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;form action=&quot;updateinfo.php&quot; method=&quot;post&quot;&gt;
userid:&lt;br/&gt;
&lt;input type=&quot;text&quot; value=&quot;&lt;?php echo $id;?&gt;&quot; name=&quot;id&quot; disabled/&gt;
&lt;br/&gt;
Last Name:&lt;br/&gt;
&lt;input type=&quot;text&quot; value=&quot;&lt;?php echo $fname;?&gt;&quot; name=&quot;fname&quot;/&gt;
&lt;br/&gt;
Last Name:&lt;br/&gt;
&lt;input type=&quot;text&quot; value=&quot;&lt;?php echo $lname;?&gt;&quot; name=&quot;lname&quot;/&gt;
&lt;br/&gt;
Phone Number:&lt;br/&gt;
&lt;input type=&quot;text&quot; value=&quot;&lt;?php echo $phone;?&gt;&quot; name=&quot;phon&quot;/&gt;
&lt;/br&gt;
&lt;input type=&quot;submit&quot; value=&quot;submit changes&quot;/&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Now you should have you fields populated. The next step is to create the updateinfo.php file and actually update some data. We will start by capturing the data. First connect to your database.</p>
<pre class="brush: php;">
&lt;?php
mysql_connect(&quot;localhost&quot;,&quot;USERNAME&quot;,&quot;PASSWORD&quot;) or die(&quot;Error: &quot;.mysql_error()); //add your DB username and password
mysql_select_db(&quot;DBNAME&quot;);//add your dbname
//get the variables we transmitted from the form
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$phon = $_POST['phon'];
?&gt;
</pre>
<p>Build the update query and execute.</p>
<pre class="brush: php;">
&lt;?php
mysql_connect(&quot;localhost&quot;,&quot;USERNAME&quot;,&quot;PASSWORD&quot;) or die(&quot;Error: &quot;.mysql_error()); //add your DB username and password
mysql_select_db(&quot;DBNAME&quot;);//add your dbname
//get the variables we transmitted from the form
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$phon = $_POST['phon'];
//replace TestTable with the name of your table
//replace id with the ID of your user
$sql = &quot;UPDATE `TestTable` SET `FName` = '$fname',`LName` = '$lname',`PHON` = '$phon' WHERE `TestTable`.`ID` = '$id' LIMIT 1&quot;;
mysql_query($sql) or die (&quot;Error: &quot;.mysql_error());
echo &quot;Database updated. &lt;a href='editinfo.php'&gt;Return to edit info&lt;/a&gt;&quot;;
?&gt;
</pre>
<p>That is all you need to allow a user to update their info. Now this is a very basic version. If you were to use this on a production web site you would want to do form validation and also protect yourself from sql injection in the update form.</p>
<p>Here is the full source for both files:</p>
<p>editinfo.php</p>
<pre class="brush: xml;">
&lt;?php
//replace usernaem,password, and yourdb with the information for your database
mysql_connect(&quot;localhost&quot;,&quot;USERNAME&quot;,&quot;PASSWORD&quot;) or die(&quot;Error: &quot;.mysqlerror());
mysql_select_db(&quot;YOURDB&quot;);
//replace TestTable with the name of your table
//also in a real app you would get the id dynamically
$sql = &quot;select * from `TestTable` where ID = 1&quot;;
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)){
	$id = $row['ID'];
	$fname = $row['FName'];
	$lname = $row['LName'];
	$phone = $row['PHON'];
	//we will echo these into the proper fields
}
mysql_free_result($query);
?&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Edit User Info&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;form action=&quot;updateinfo.php&quot; method=&quot;post&quot;&gt;
userid:&lt;br/&gt;
&lt;input type=&quot;text&quot; value=&quot;&lt;?php echo $id;?&gt;&quot; name=&quot;id&quot; disabled/&gt;
&lt;br/&gt;
Last Name:&lt;br/&gt;
&lt;input type=&quot;text&quot; value=&quot;&lt;?php echo $fname;?&gt;&quot; name=&quot;fname&quot;/&gt;
&lt;br/&gt;
Last Name:&lt;br/&gt;
&lt;input type=&quot;text&quot; value=&quot;&lt;?php echo $lname;?&gt;&quot; name=&quot;lname&quot;/&gt;
&lt;br/&gt;
Phone Number:&lt;br/&gt;
&lt;input type=&quot;text&quot; value=&quot;&lt;?php echo $phone;?&gt;&quot; name=&quot;phon&quot;/&gt;
&lt;/br&gt;
&lt;input type=&quot;submit&quot; value=&quot;submit changes&quot;/&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>updateinfo.php</p>
<pre class="brush: php;">
&lt;?php
//replace usernaem,password, and yourdb with the information for your database
mysql_connect(&quot;localhost&quot;,&quot;USERNAME&quot;,&quot;PASSWORD&quot;) or die(&quot;Error: &quot;.mysqlerror());
mysql_select_db(&quot;YOURDB&quot;);
//get the variables we transmitted from the form
$id = $_POST['id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$phon = $_POST['phon'];
//replace TestTable with the name of your table
$sql = &quot;UPDATE `TestTable` SET `FName` = '$fname',`LName` = '$lname',`PHON` = '$phon' WHERE `TestTable`.`ID` = '$id' LIMIT 1&quot;;
mysql_query($sql) or die (&quot;Error: &quot;.mysql_error());
echo &quot;Database updated. &lt;a href='editinfo.php'&gt;Return to edit info&lt;/a&gt;&quot;;
?&gt;
</pre>
<p>If you are going to ask a question please take the time to go through the tutorial first. Thanks.</p>
<h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://teamtutorials.com/web-development-tutorials/php-tutorials/creating-a-form-that-will-search-a-mysql-database" title="Creating a Form that will Search a MySQL Database">Creating a Form that will Search a MySQL Database</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/how-to-return-mysql-results-to-a-table" title="How to Return MySQL Results to a Table">How to Return MySQL Results to a Table</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/creating-checkboxes-based-on-sql-results" title="Creating Checkboxes Based on SQL Results">Creating Checkboxes Based on SQL Results</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/setting-up-a-wamp-server" title="Setting Up a WAMP Server">Setting Up a WAMP Server</a></li><li><a href="http://teamtutorials.com/database-tutorials/referential-integrity-with-mysql" title="Referential Integrity with MySQL">Referential Integrity with MySQL</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://teamtutorials.com/web-development-tutorials/editing-mysql-data-using-php/feed</wfw:commentRss>
		<slash:comments>52</slash:comments>
		</item>
		<item>
		<title>How to Get a Users Geo Location?</title>
		<link>http://teamtutorials.com/web-development-tutorials/how-to-get-a-users-geo-location</link>
		<comments>http://teamtutorials.com/web-development-tutorials/how-to-get-a-users-geo-location#comments</comments>
		<pubDate>Mon, 23 Feb 2009 00:27:29 +0000</pubDate>
		<dc:creator>John Ward</dc:creator>
				<category><![CDATA[PHP Tutorials]]></category>
		<category><![CDATA[SEO Tutorials]]></category>
		<category><![CDATA[Web Development Tutorials]]></category>
		<category><![CDATA[geo code]]></category>
		<category><![CDATA[geo location]]></category>
		<category><![CDATA[geocoding]]></category>
		<category><![CDATA[max mind]]></category>
		<category><![CDATA[php]]></category>
		<guid isPermaLink="false">http://teamtutorials.com/?p=1767</guid>
		<description><![CDATA[Every wonder how all of those dating ads know that you are looking for hot girls near (insert your city here)? Well if you are a complete nerd like me you probably ignored the hot girls and wondered: “How did they know where I live?”. There are a few simple ways to do this. Today [...]]]></description>
			<content:encoded><![CDATA[<p>Every wonder how all of those dating ads know that you are looking for hot girls near (insert your city here)? Well if you are a complete nerd like me you probably ignored the hot girls and wondered: “How did they know where I live?”. There are a few simple ways to do this. Today I am going to show you how to GeoCode using MaxMind&#8217;s free version.</p>
<p>MaxMind offers a paid version of this script that probably offers much more functionality. For what I need though, the free database does the job. I checked the results via a few proxies and they matched the US city fine. I am not sure how this works with international visitors, but I use it for US targeted traffic (It does pick up Canadian cities and Provinces fine….eh)..</p>
<p>First off you are going to need to download the Database and PHP API code:</p>
<p><a href="http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz">MaxMind GeoLiteCity</a><br />
<a href=" http://geolite.maxmind.com/download/geoip/api/php/geoip.inc">Geoip.inc</a><br />
<a href=" http://geolite.maxmind.com/download/geoip/api/php/geoipcity.inc">Geoipcity.php</a><br />
<a href="http://geolite.maxmind.com/download/geoip/api/php/geoipregionvars.php">Geoipregionvars.php</a></p>
<p>Once you download all of the files. Extract them all and upload them to the same folder on your server.</p>
<p>Now to use the API we need to include a few files. Then we are going to open the database and check the users location:</p>
<pre class="brush: php;">
include(&quot;geoip.inc&quot;);
include(&quot;geoipcity.inc&quot;);
include(&quot;geoipregionvars.php&quot;);
$gi = geoip_open(&quot;./GeoLiteCity.dat&quot;, GEOIP_STANDARD);
$rsGeoData = geoip_record_by_addr($gi, $_SERVER['REMOTE_ADDR']);
geoip_close($gi);
</pre>
<p>This will grab the information, but what can we do with it. To find out what variables you can use print out the array:</p>
<pre class="brush: php;">
include(&quot;geoip.inc&quot;);
include(&quot;geoipcity.inc&quot;);
include(&quot;geoipregionvars.php&quot;);
$gi = geoip_open(&quot;./GeoLiteCity.dat&quot;, GEOIP_STANDARD);
$rsGeoData = geoip_record_by_addr($gi, $_SERVER['REMOTE_ADDR']);
geoip_close($gi);
print &quot;&lt;pre&gt;&quot;;
print_r($rsGeoData);
print &quot;&lt;/pre&gt;&quot;;
</pre>
<p>The results should output something like this:</p>
<pre>
geoiprecord Object
(
    [country_code] => US
    [country_code3] => USA
    [country_name] => United States
    [region] => TN
    [city] => Memphis
    [postal_code] =>
    [latitude] => 35.1242
    [longitude] => -89.9521
    [area_code] => 901
    [dma_code] => 640
)
</pre>
<p>I ran the above code using a Memphis based proxy. As you can see MaxMinds database gives us:<br />
Country Abbreviation in two formats,<br />
Full country name,<br />
Region (state/province),<br />
City,<br />
Postal code (this usually works but is blank in the example),<br />
Latitude,<br />
Longitude,<br />
Area Code,<br />
DMA code (Designated Market Area as in Nielsen Media tv/radio market areas in the US)</p>
<p>Ok so now that we know what everything is, all we have to do is echo the results in the proper places. For example:</p>
<pre class="brush: php;">
echo $rsGeoData-&gt;city;
echo ' ,';
echo $rsGeoData-&gt;region;
</pre>
<p>Would out put:  Memphis, TN.<br />
So if you were going to use this in a template you would use something like this in the header:</p>
<pre class="brush: php;">
&lt;?php
include(&quot;geoip.inc&quot;);
include(&quot;geoipcity.inc&quot;);
include(&quot;geoipregionvars.php&quot;);
$gi = geoip_open(&quot;./GeoLiteCity.dat&quot;, GEOIP_STANDARD);
$rsGeoData = geoip_record_by_addr($gi, $_SERVER['REMOTE_ADDR']);
geoip_close($gi);
$location =  $rsGeoData-&gt;city.','.$rsGeoData-&gt;region;
?&gt;
</pre>
<p>Then in your template wherever you want the City, State to display simple:</p>
<pre class="brush: xml;">
&lt;h1&gt;Meet girls near &lt;?php echo $location;?&gt;&lt;/h1&gt;
</pre>
<p>The your site might look something like this:<br />
<img src="http://teamtutorials.com/wp-content/uploads/2009/02/phpgeocoding.jpg" alt="php geo coding" title="php geo coding" width="532" height="169" class="alignnone size-full wp-image-1768" /></p>
<h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://teamtutorials.com/web-development-tutorials/using-jquery-to-reorder-a-list-and-update-a-database" title="Using jQuery to Reorder a List and Update a Database">Using jQuery to Reorder a List and Update a Database</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/sending-e-mail-to-validate-user-sign-up" title="Sending E-Mail to validate User Sign-up">Sending E-Mail to validate User Sign-up</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/how-to-parse-a-csv-file-using-php" title="How to Parse a CSV File Using PHP">How to Parse a CSV File Using PHP</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/how-to-return-mysql-results-to-a-table" title="How to Return MySQL Results to a Table">How to Return MySQL Results to a Table</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/editing-mysql-data-using-php" title="Editing MySQL Data Using PHP">Editing MySQL Data Using PHP</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://teamtutorials.com/web-development-tutorials/how-to-get-a-users-geo-location/feed</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Convert a MySQL date field using PHP Functions</title>
		<link>http://teamtutorials.com/web-development-tutorials/convert-a-mysql-date-field-using-php-functions</link>
		<comments>http://teamtutorials.com/web-development-tutorials/convert-a-mysql-date-field-using-php-functions#comments</comments>
		<pubDate>Fri, 20 Feb 2009 06:52:04 +0000</pubDate>
		<dc:creator>John Ward</dc:creator>
				<category><![CDATA[Database Tutorials]]></category>
		<category><![CDATA[PHP Tutorials]]></category>
		<category><![CDATA[Web Development Tutorials]]></category>
		<guid isPermaLink="false">http://teamtutorials.com/?p=1752</guid>
		<description><![CDATA[Today I am going to show you how to convert data returned from a MySQL database that was store as a date data type into a user friendly format. To do this you can take two different approaches. One way to do it is to use the function date_format() function in your query. The other way to to modify the date after it is returned.]]></description>
			<content:encoded><![CDATA[<p>Today I am going to show you how to convert data returned from a MySQL database that was store as a date data type into a user friendly format. To do this you can take two different approaches. One way to do it is to use the function date_format() function in your query. The other way to to modify the date after it is returned.</p>
<p>Since you are trying to convert the date I am assuming you can connect to a database, runa  query, and display the results. If not check out some of our older tutorials:</p>
<h2><a href="http://teamtutorials.com/web-development-tutorials/how-to-access-a-mysql-database-using-php">How to Access a MySQL Database Using PHP</a></h2>
<h2><a href="http://teamtutorials.com/web-development-tutorials/php-tutorials/inserting-data-into-a-mysql-database-using-php">Creating a Form that will Search a MySQL Database</a></h2>
<p>You can use the function in the query to convert the date or after the results are returned.</p>
<p>Using date_format() </p>
<p>Here is an example of how to call the function in a query:</p>
<pre class="brush: php;">
$query = mysql_query(&quot;select * date_format(date, '%b %d') as newdate from `table`&quot;)
</pre>
<p>Then when your results are returned simple echo $row[newdate]. The date I used will output the date in this format: Feb 18th (abbreviated month and numeric day with suffix).<br />
You need to pass the date string and the format mask to the function: date_format($date, $format)</p>
<p>You can pretty much do this the same way after your results are returned.<br />
For example:</p>
<pre class="brush: php;">
	$query = mysql_query(&quot;select * from `table` &quot;);
	while ($row = mysql_fetch_array($query)){
		$newdate = date_format(strtotime($row[date]), '%b %d');
	}
</pre>
<p>strtotime will convert a string date to a time stamp.</p>
<p>Other formatting option for date_format()</p>
<table style="border: 1px #ccc solid;padding:1px;">
<tr>
<th style="border: 1px #ccc solid;background:#39f">Specifier</th>
<th style="border: 1px #ccc solid;background:#39F">Description</th>
</tr>
<tr>
<td style="border: 1px #ccc solid;">%a</td>
<td style="border: 1px #ccc solid;">Abbreviated weekday name (Sun..Sat)</td>
</tr>
<tr>
<td style="border: 1px #ccc solid;">%b</td>
<td style="border: 1px #ccc solid;">Abbreviated month name (Jan..Dec)</td>
</tr>
<tr>
<td style="border: 1px #ccc solid;">%c</td>
<td style="border: 1px #ccc solid;">Month, numeric (0..12)</td>
</tr>
<tr>
<td style="border: 1px #ccc solid;">%D</td>
<td style="border: 1px #ccc solid;">Day of the month with English suffix (0th, 1st, 2nd, 3rd, …)</td>
</tr>
<tr>
<td style="border: 1px #ccc solid;">%d</td>
<td style="border: 1px #ccc solid;">Day of the month, numeric (00..31)</td>
</tr>
<tr>
<td style="border: 1px #ccc solid;">%e</td>
<td style="border: 1px #ccc solid;">Day of the month, numeric (0..31)</td>
</tr>
<tr>
<td style="border: 1px #ccc solid;">%f</td>
<td style="border: 1px #ccc solid;">Microseconds (000000..999999)</td>
</tr>
<tr>
<td style="border: 1px #ccc solid;">%H</td>
<td style="border: 1px #ccc solid;">Hour (00..23)</td>
</tr>
<tr>
<td style="border: 1px #ccc solid;">%h</td>
<td style="border: 1px #ccc solid;">Hour (01..12)</td>
</tr>
<tr>
<td style="border: 1px #ccc solid;">%I</td>
<td style="border: 1px #ccc solid;">Hour (01..12)</td>
</tr>
<tr>
<td style="border: 1px #ccc solid;">%i</td>
<td style="border: 1px #ccc solid;">Minutes, numeric (00..59)</td>
</tr>
<tr>
<td style="border: 1px #ccc solid;">%j</td>
<td style="border: 1px #ccc solid;">Day of year (001..366)</td>
</tr>
<tr>
<td style="border: 1px #ccc solid;">%k</td>
<td style="border: 1px #ccc solid;">Hour (0..23)</td>
</tr>
<tr>
<td style="border: 1px #ccc solid;">%l</td>
<td style="border: 1px #ccc solid;">Hour (1..12)</td>
</tr>
<tr>
<td style="border: 1px #ccc solid;">%M</td>
<td style="border: 1px #ccc solid;">Month name (January..December)</td>
</tr>
<tr>
<td style="border: 1px #ccc solid;">%m</td>
<td style="border: 1px #ccc solid;">Month, numeric (00..12)</td>
</tr>
<tr>
<td style="border: 1px #ccc solid;">%p</td>
<td style="border: 1px #ccc solid;">AM or PM</td>
</tr>
<tr>
<td style="border: 1px #ccc solid;">%r</td>
<td style="border: 1px #ccc solid;">Time, 12-hour (hh:mm:ss followed by AM or PM)</td>
</tr>
<tr>
<td style="border: 1px #ccc solid;">%S</td>
<td style="border: 1px #ccc solid;">Seconds (00..59)</td>
</tr>
</table>
<p>edit:<br />
This can also be done using the date function. Something like:</p>
<p>		$day = date(&#8220;d&#8221;,strtotime($row['date']));<br />
		$month = date(&#8220;M&#8221;,strtotime($row['date']));</p>
<p>would give you Mar 03</p>
<h2  class="related_post_title">Other Related Tutorials</h2><ul class="related_post"><li><a href="http://teamtutorials.com/programming-tutorials/basic-vb-code-%e2%80%93-changing-text" title="Basic VB Code – Changing Text">Basic VB Code – Changing Text</a></li><li><a href="http://teamtutorials.com/photoshop-tutorials/versus-inspired-photoshop-logo-tutorial" title="Versus Inspired Photoshop Logo Tutorial">Versus Inspired Photoshop Logo Tutorial</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/validating-email-address-with-php-and-ajax" title="Validating Email Address with PHP and AJAX">Validating Email Address with PHP and AJAX</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/how-to-access-a-mysql-database-using-php" title="How to Access a MySQL Database Using PHP">How to Access a MySQL Database Using PHP</a></li><li><a href="http://teamtutorials.com/windows-tutorials/set-windows-xp-program-access-and-defaults" title="Set Windows XP Program Access and Defaults">Set Windows XP Program Access and Defaults</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://teamtutorials.com/web-development-tutorials/convert-a-mysql-date-field-using-php-functions/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Creating Checkboxes Based on SQL Results</title>
		<link>http://teamtutorials.com/web-development-tutorials/creating-checkboxes-based-on-sql-results</link>
		<comments>http://teamtutorials.com/web-development-tutorials/creating-checkboxes-based-on-sql-results#comments</comments>
		<pubDate>Mon, 22 Sep 2008 02:14:36 +0000</pubDate>
		<dc:creator>Mike Maguire</dc:creator>
				<category><![CDATA[PHP Tutorials]]></category>
		<category><![CDATA[Web Development Tutorials]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>
		<guid isPermaLink="false">http://teamtutorials.com/?p=1664</guid>
		<description><![CDATA[This tutorial will walk you through creating a database of categories and then using the categories in the database to create a series of checkboxes. This could be used for forum or board that will allow them to select a category of their story/comment.]]></description>
			<content:encoded><![CDATA[<p>This tutorial will walk you through creating a database of categories and then using the categories in the database to create a series of checkboxes. This could be used for forum or board that will allow them to select a category of their story/comment. Let’s begin.</p>
<p>I will be doing all of this code and execution on my local PC thanks to WAMP Server which can be installed by following <a href="http://teamtutorials.com/web-development-tutorials/setting-up-a-wamp-server">Installing a WAMP Server</a>. To get started we will need to create our database. To do this, run the following in your SQL editor:</p>
<pre class="brush: sql;">
SET SQL_MODE=&quot;NO_AUTO_VALUE_ON_ZERO&quot;;
CREATE TABLE `tutorial` (
  `CatID` int(3) NOT NULL auto_increment,
  `Category` varchar(100) NOT NULL,
  PRIMARY KEY  (`CatID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;
INSERT INTO `tutorial` (`CatID`, `Category`) VALUES
(1, 'Cars'),
(2, 'Trucks'),
(3, 'Baseball'),
(4, 'Basketball'),
(5, 'Football'),
(6, 'Houses'),
(7, 'Root Beer'),
(8, 'Gatorade'),
(9, 'Speakers'),
(10, 'Computers'),
(11, 'Databases'),
(12, 'Software');
</pre>
<p>This will create our table that we will be using for this tutorial. Now we need to create the file that will pull these values to our site and show them in an orderly fashion. Create an index.php in your www root of your WAMP server and open it in your favorite text editor. </p>
<pre class="brush: php;">
&lt;?php
$conn = mysql_connect (&quot;localhost&quot;,&quot;user_name&quot;,&quot;password&quot;) or die ('cannot connect to database error: '.mysql_error());
mysql_select_db (&quot;tutorial&quot;);
$sql = 'select * from `tutorial` order by Category';
$result = mysql_query($sql);
if (!$result) {
    echo &quot;DB Error, could not list customers\n&quot;;
    echo 'MySQL Error: ' . mysql_error();
    exit;
}
$cats = 1
?&gt;
</pre>
<p>This first section of the file simply creates the connection to the database and select all the categories from the table named tutorial (which we just created). It sets all the results to the variable of results. Make sure you change the code to have your databases user name and password in the proper locations. If it receives no results it throws an error and displays it to the browser window. The final thing you see is that we created a variable of cats so that we can keep track of how many items have been inserted.</p>
<pre class="brush: xml;">
&lt;form name=&quot;category&quot; method=&quot;post&quot; action=&quot;insert.php&quot;&gt;
Select your story topic(s)&lt;br /&gt;&lt;br /&gt;
&lt;table border = &quot;1&quot; cellpadding = &quot;5&quot;&gt;
&lt;tr&gt;
</pre>
<p>Next, we set up our form. Then we create a table so that the items can be aligned properly. </p>
<pre class="brush: php;">
&lt;?php
while ($row = mysql_fetch_row($result))
{
if (($cats / 3) == 1){
	echo &quot;&lt;td align = 'right'&gt;$row[1]:&lt;input type='checkbox' name=$row[1] value=$row[1] /&gt; &lt;br /&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&quot;;
	$cats = 1;
}
else
{
	echo &quot;&lt;td align = 'right'&gt;$row[1]:&lt;input type='checkbox' name=$row[1] value=$row[1] /&gt; &lt;br /&gt;&lt;/td&gt;&quot;;
	$cats++;
}
}
mysql_free_result($result);
?&gt;
</pre>
<p>This section so to process everything in the brackets of the “while” clause to be executed until $row (the results returned from our query) contains no information. The first line of the while clause checks to see if this is the third category we have entered since we declared cats to be 1. If it is, it echoes the line after it which shows the category in a column and then ends the row and starts a new one. Otherwise, it just puts the value in a new column and leaves the row tag open and increments the variable by one. This way every third category will be placed on a new row. The final line clears the results from the variable.</p>
<pre class="brush: xml;">
&lt;/tr&gt;&lt;/table&gt;&lt;br /&gt;&lt;br /&gt;
&lt;input type='submit' value='Insert Comment'&gt;
&lt;/form&gt;
</pre>
<p>Then we close the final row and end the table. Then we create a couple of breaks and make the submit button to allow the user to submit the values and finally close the form. If you have followed these steps you should get a page similar to this:</p>
<p><a href="http://teamtutorials.com/wp-content/uploads/2008/09/creating_checkboxes_from_sql_results_01.jpg"><img src="http://teamtutorials.com/wp-content/uploads/2008/09/creating_checkboxes_from_sql_results_01.jpg" alt="creating_checkboxes_from_sql_results_01" title="creating_checkboxes_from_sql_results_01" width="320" height="274" class="size-medium wp-image-1665" /></a></p>
<p>If you go into the database and add more items, or change the items in there the page will automatically show your changes without the need to change the code like below:</p>
<p><a href="http://teamtutorials.com/wp-content/uploads/2008/09/creating_checkboxes_from_sql_results_02.jpg"><img src="http://teamtutorials.com/wp-content/uploads/2008/09/creating_checkboxes_from_sql_results_02.jpg" alt="" title="creating_checkboxes_from_sql_results_02" width="325" height="320" class="alignnone size-medium wp-image-1666" /></a></p>
<p>This concludes this tutorial. We will continue to take this a step further in the next tutorial. If you have any questions, please leave a comment. I hope this was easy to follow and thanks for reading.</p>
<h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://teamtutorials.com/web-development-tutorials/using-jquery-to-reorder-a-list-and-update-a-database" title="Using jQuery to Reorder a List and Update a Database">Using jQuery to Reorder a List and Update a Database</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/how-to-return-mysql-results-to-a-table" title="How to Return MySQL Results to a Table">How to Return MySQL Results to a Table</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/editing-mysql-data-using-php" title="Editing MySQL Data Using PHP">Editing MySQL Data Using PHP</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/jquery-pop-over-effects" title="jQuery Pop Over Effects">jQuery Pop Over Effects</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/password-verification-and-strength-checker" title="Password Verification and Strength Checker">Password Verification and Strength Checker</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://teamtutorials.com/web-development-tutorials/creating-checkboxes-based-on-sql-results/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Simple PHP Website Templates</title>
		<link>http://teamtutorials.com/web-development-tutorials/simple-php-website-templates</link>
		<comments>http://teamtutorials.com/web-development-tutorials/simple-php-website-templates#comments</comments>
		<pubDate>Mon, 25 Aug 2008 17:10:50 +0000</pubDate>
		<dc:creator>John Ward</dc:creator>
				<category><![CDATA[HTML Tutorials]]></category>
		<category><![CDATA[PHP Tutorials]]></category>
		<category><![CDATA[Web Development Tutorials]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[templates]]></category>
		<guid isPermaLink="false">http://teamtutorials.com/?p=1647</guid>
		<description><![CDATA[So you have a basic HTML site with 100 pages, what happens when you want to change the title tag? Well, if you aren’t using PHP includes, you will have to update each file. Wouldn’t it be nice if you could make the change to one file and it would update every page? That is what we will accomplish with our basic PHP template tutorial.]]></description>
			<content:encoded><![CDATA[<p>So you have a basic HTML site with 100 pages, what happens when you want to change the title tag? Well, if you aren&#8217;t using PHP includes, you will have to update each file. Wouldn&#8217;t it be nice if you could make the change to one file and it would update every page? That is what we will accomplish with our basic PHP template tutorial.</p>
<p>This tutorial will require a server that can handle PHP code. If you would like to set one up on your computer, check out Mike&#8217;s “<a href="http://teamtutorials.com/web-development-tutorials/setting-up-a-wamp-server">Installing WAMP tutorial</a>”.</p>
<p>First, if you don&#8217;t have a website that you would like to break up into a template, you can use the sample<a href="http://www.456bereastreet.com/lab/developing_with_web_standards/csslayout/2-col/"> 2 column layout </a>below from 456bereastreet.com </p>
<pre class="brush: xml;">
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot;
        &quot;http://www.w3.org/TR/html4/strict.dtd&quot;&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
	&lt;title&gt;Simple 2 column CSS layout, final layout | 456 Berea Street&lt;/title&gt;
	&lt;meta name=&quot;description&quot; content=&quot;How to create a simple two column CSS layout with full width header and footer.&quot;&gt;
	&lt;meta name=&quot;copyright&quot; content=&quot;Copyright (c) 2004 Roger Johansson&quot;&gt;
	&lt;meta name=&quot;author&quot; content=&quot;Roger Johansson&quot;&gt;
	&lt;style type=&quot;text/css&quot;&gt;
	body,
	html {
		margin:0;
		padding:0;
		background:#a7a09a;
		color:#000;
	}
	body {
		min-width:750px;
	}
	#wrap {
		background:#99c;
		margin:0 auto;
		width:750px;
	}
	#header {
		background:#ddd;
	}
	#header h1 {
    	padding:5px;
	    margin:0;
    }
	#nav {
		background:#c99;
		padding:5px;
	}
	#nav ul{
		margin:0;
		padding:0;
		list-style:none;
	}
	#nav li{
		display:inline;
		margin:0;
		padding:0;
	}
	#main {
		background:#9c9;
		float:left;
		width:500px;
	}
	#main h2, #main h3, #main p {
		padding:0 10px;
    }
	#sidebar {
		background:#99c;
		float:right;
		width:240px;
	}
	#sidebar ul {
		margin-bottom:0;
    }
    #sidebar h3, #sidebar p {
		padding:0 10px 0 0;
    }
	#footer {
		background:#cc9;
		clear:both;
	}
	#footer p {
		padding:5px;
		margin:0;
    }
	&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div id=&quot;wrap&quot;&gt;
	&lt;div id=&quot;header&quot;&gt;&lt;h1&gt;Simple 2 column CSS layout, final layout&lt;/h1&gt;&lt;/div&gt;
	&lt;div id=&quot;nav&quot;&gt;
		&lt;ul&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Option 1&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Option 2&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Option 3&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Option 4&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Option 5&lt;/a&gt;&lt;/li&gt;
		&lt;/ul&gt;
	&lt;/div&gt;
	&lt;div id=&quot;main&quot;&gt;
		&lt;h2&gt;Column 1&lt;/h2&gt;
		&lt;p&gt;&lt;a href=&quot;/&quot;&gt;456 Berea Street Home&lt;/a&gt; | &lt;a href=&quot;/lab/developing_with_web_standards/csslayout/2-col/&quot;&gt;Simple 2 column CSS layout&lt;/a&gt; | &lt;a href=&quot;http://www.456bereastreet.com/lab/developing_with_web_standards/&quot;&gt;Developing with web standards index&lt;/a&gt;&lt;/p&gt;
		&lt;p&gt;Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Mauris vel magna. Mauris risus nunc, tristique varius, gravida in, lacinia vel, elit. Nam ornare, felis non faucibus molestie, nulla augue adipiscing mauris, a nonummy diam ligula ut risus. Praesent varius. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.&lt;/p&gt;
		&lt;p&gt;Nulla a lacus. Nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce pulvinar lobortis purus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec semper ipsum et urna. Ut consequat neque vitae felis. Suspendisse dapibus, magna quis pulvinar laoreet, dolor neque lacinia arcu, et luctus mi erat vestibulum sem. Mauris faucibus iaculis lacus. Aliquam nec ante in quam sollicitudin congue. Quisque congue egestas elit. Quisque viverra. Donec feugiat elementum est. Etiam vel lorem.&lt;/p&gt;
		&lt;p&gt;Aenean tempor. Mauris tortor quam, elementum eu, convallis a, semper quis, purus. Cras at tortor in purus tincidunt tristique. In hac habitasse platea dictumst. Ut eu lectus eu metus molestie iaculis. In ornare. Donec at enim vel erat tempor congue. Nullam varius. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla feugiat hendrerit risus. Integer enim velit, gravida id, sollicitudin at, consequat sit amet, leo. Fusce imperdiet condimentum velit. Phasellus nonummy interdum est. Pellentesque quam.&lt;/p&gt;
		&lt;h3&gt;Consectetuer adipiscing elit&lt;/h3&gt;
		&lt;p&gt;Nulla dictum. Praesent turpis libero, pretium in, pretium ac, malesuada sed, ligula. Sed a urna eu ipsum luctus faucibus. Curabitur fringilla. Suspendisse sit amet quam. Sed vel pede id libero luctus fermentum. Vestibulum volutpat tempor lectus. Vivamus convallis tempus ante. Nullam adipiscing dui blandit ipsum. Nullam convallis lacus ut quam. Mauris semper elit at ante. Vivamus tristique. Pellentesque pharetra ante at pede. In ultrices arcu vitae purus. In rutrum, erat at mollis consequat, leo massa consequat libero, ac vestibulum libero tellus sed risus. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.&lt;/p&gt;
		&lt;p&gt;Maecenas eu velit nec magna venenatis consequat. In neque. Vivamus pellentesque, lacus eu aliquet semper, lorem metus rhoncus metus, a ornare orci ante a diam. Nunc sem nisl, aliquet quis, elementum nec, imperdiet in, wisi. Proin in lorem. Etiam molestie diam eget ante. Morbi quis tortor id lacus mollis venenatis. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam vel orci sit amet tellus mollis eleifend. Donec urna diam, viverra eget, ultricies gravida, ultrices eu, erat. Proin vel arcu. Sed diam. Cras hendrerit arcu sed augue. Sed justo felis, luctus a, accumsan in, tincidunt facilisis, libero. Phasellus eu eros.&lt;/p&gt;
	&lt;/div&gt;
	&lt;div id=&quot;sidebar&quot;&gt;
		&lt;h3&gt;Column 2&lt;/h3&gt;
		&lt;p&gt;Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Mauris vel magna.&lt;/p&gt;
		&lt;ul&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 1&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 2&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 3&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 4&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 5&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 6&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 7&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 8&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 9&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 10&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 11&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 12&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 13&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 14&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 15&lt;/a&gt;&lt;/li&gt;
		&lt;/ul&gt;
	&lt;/div&gt;
	&lt;div id=&quot;footer&quot;&gt;
		&lt;p&gt;Footer&lt;/p&gt;
	&lt;/div&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>We are going to break the page up into individual files, and then use PHP includes to join them again. Here is a break down of how the files will be separated.</p>
<p><a href="http://teamtutorials.com/wp-content/uploads/2008/08/php-templates-1.jpg"><img src="http://teamtutorials.com/wp-content/uploads/2008/08/php-templates-1.jpg" alt="" title="php-templates-1" width="500" height="305" class="alignnone size-full wp-image-1648" /></a></p>
<p>The first step is to is to create a new PHP file. This file will be for the header, so I will name it header.php (you could also name these header.inc if you would like). We will cut all of the code from the beginning HTML tag all the way down to the end of the header section and paste it in this file. The file should look like this:</p>
<pre class="brush: xml;">
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot;
        &quot;http://www.w3.org/TR/html4/strict.dtd&quot;&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
	&lt;title&gt;Simple 2 column CSS layout, final layout | 456 Berea Street&lt;/title&gt;
	&lt;meta name=&quot;description&quot; content=&quot;How to create a simple two column CSS layout with full width header and footer.&quot;&gt;
	&lt;meta name=&quot;copyright&quot; content=&quot;Copyright (c) 2004 Roger Johansson&quot;&gt;
	&lt;meta name=&quot;author&quot; content=&quot;Roger Johansson&quot;&gt;
	&lt;style type=&quot;text/css&quot;&gt;
	body,
	html {
		margin:0;
		padding:0;
		background:#a7a09a;
		color:#000;
	}
	body {
		min-width:750px;
	}
	#wrap {
		background:#99c;
		margin:0 auto;
		width:750px;
	}
	#header {
		background:#ddd;
	}
	#header h1 {
    	padding:5px;
	    margin:0;
    }
	#nav {
		background:#c99;
		padding:5px;
	}
	#nav ul{
		margin:0;
		padding:0;
		list-style:none;
	}
	#nav li{
		display:inline;
		margin:0;
		padding:0;
	}
	#main {
		background:#9c9;
		float:left;
		width:500px;
	}
	#main h2, #main h3, #main p {
		padding:0 10px;
    }
	#sidebar {
		background:#99c;
		float:right;
		width:240px;
	}
	#sidebar ul {
		margin-bottom:0;
    }
    #sidebar h3, #sidebar p {
		padding:0 10px 0 0;
    }
	#footer {
		background:#cc9;
		clear:both;
	}
	#footer p {
		padding:5px;
		margin:0;
    }
	&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div id=&quot;wrap&quot;&gt;
	&lt;div id=&quot;header&quot;&gt;&lt;h1&gt;Simple 2 column CSS layout, final layout&lt;/h1&gt;&lt;/div&gt;
</pre>
<p>Next we will cut the code for the top menu and paste it into a file called top-menu.php</p>
<pre class="brush: xml;">
&lt;div id=&quot;nav&quot;&gt;
		&lt;ul&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Option 1&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Option 2&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Option 3&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Option 4&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Option 5&lt;/a&gt;&lt;/li&gt;
		&lt;/ul&gt;
	&lt;/div&gt;
</pre>
<p>And the last part is to cut from the div id=”sidebar” to the end of the page and paste it in sidebar.php. You could also separate the footer into its own file, but for the is example I will include it into the sidebar.</p>
<pre class="brush: xml;">
&lt;div id=&quot;sidebar&quot;&gt;
		&lt;h3&gt;Column 2&lt;/h3&gt;
		&lt;p&gt;Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Mauris vel magna.&lt;/p&gt;
		&lt;ul&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 1&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 2&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 3&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 4&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 5&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 6&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 7&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 8&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 9&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 10&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 11&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 12&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 13&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 14&lt;/a&gt;&lt;/li&gt;
			&lt;li&gt;&lt;a href=&quot;#&quot;&gt;Link 15&lt;/a&gt;&lt;/li&gt;
		&lt;/ul&gt;
	&lt;/div&gt;
	&lt;div id=&quot;footer&quot;&gt;
		&lt;p&gt;Footer&lt;/p&gt;
	&lt;/div&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Now if you cut all of those lines, it should leave you with the following code in your original file:</p>
<pre class="brush: xml;">
	&lt;div id=&quot;main&quot;&gt;
		&lt;h2&gt;Column 1&lt;/h2&gt;
		&lt;p&gt;&lt;a href=&quot;/&quot;&gt;456 Berea Street Home&lt;/a&gt; | &lt;a href=&quot;/lab/developing_with_web_standards/csslayout/2-col/&quot;&gt;Simple 2 column CSS layout&lt;/a&gt; | &lt;a href=&quot;http://www.456bereastreet.com/lab/developing_with_web_standards/&quot;&gt;Developing with web standards index&lt;/a&gt;&lt;/p&gt;
		&lt;p&gt;Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Mauris vel magna. Mauris risus nunc, tristique varius, gravida in, lacinia vel, elit. Nam ornare, felis non faucibus molestie, nulla augue adipiscing mauris, a nonummy diam ligula ut risus. Praesent varius. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.&lt;/p&gt;
		&lt;p&gt;Nulla a lacus. Nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce pulvinar lobortis purus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec semper ipsum et urna. Ut consequat neque vitae felis. Suspendisse dapibus, magna quis pulvinar laoreet, dolor neque lacinia arcu, et luctus mi erat vestibulum sem. Mauris faucibus iaculis lacus. Aliquam nec ante in quam sollicitudin congue. Quisque congue egestas elit. Quisque viverra. Donec feugiat elementum est. Etiam vel lorem.&lt;/p&gt;
		&lt;p&gt;Aenean tempor. Mauris tortor quam, elementum eu, convallis a, semper quis, purus. Cras at tortor in purus tincidunt tristique. In hac habitasse platea dictumst. Ut eu lectus eu metus molestie iaculis. In ornare. Donec at enim vel erat tempor congue. Nullam varius. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla feugiat hendrerit risus. Integer enim velit, gravida id, sollicitudin at, consequat sit amet, leo. Fusce imperdiet condimentum velit. Phasellus nonummy interdum est. Pellentesque quam.&lt;/p&gt;
		&lt;h3&gt;Consectetuer adipiscing elit&lt;/h3&gt;
		&lt;p&gt;Nulla dictum. Praesent turpis libero, pretium in, pretium ac, malesuada sed, ligula. Sed a urna eu ipsum luctus faucibus. Curabitur fringilla. Suspendisse sit amet quam. Sed vel pede id libero luctus fermentum. Vestibulum volutpat tempor lectus. Vivamus convallis tempus ante. Nullam adipiscing dui blandit ipsum. Nullam convallis lacus ut quam. Mauris semper elit at ante. Vivamus tristique. Pellentesque pharetra ante at pede. In ultrices arcu vitae purus. In rutrum, erat at mollis consequat, leo massa consequat libero, ac vestibulum libero tellus sed risus. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.&lt;/p&gt;
		&lt;p&gt;Maecenas eu velit nec magna venenatis consequat. In neque. Vivamus pellentesque, lacus eu aliquet semper, lorem metus rhoncus metus, a ornare orci ante a diam. Nunc sem nisl, aliquet quis, elementum nec, imperdiet in, wisi. Proin in lorem. Etiam molestie diam eget ante. Morbi quis tortor id lacus mollis venenatis. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam vel orci sit amet tellus mollis eleifend. Donec urna diam, viverra eget, ultricies gravida, ultrices eu, erat. Proin vel arcu. Sed diam. Cras hendrerit arcu sed augue. Sed justo felis, luctus a, accumsan in, tincidunt facilisis, libero. Phasellus eu eros.&lt;/p&gt;
	&lt;/div&gt;
</pre>
<p>So now we have all of the code broken down into include files. How do we put them all back together?</p>
<p>Create a file called template.php, we will use this as the template to build each content page. Now we just have to include the pages we just created. When using include, the web server will render the code from the included pages before the browser interprets it. You will see later that the source code will be identical if viewed in the browser.</p>
<p>This is what your template.php file should look like:</p>
<pre class="brush: xml;">
&lt;?php include('header.php');?&gt;
&lt;?php include('top-menu.php');?&gt;
	&lt;div id=&quot;main&quot;&gt;
		&lt;h2&gt;Column 1&lt;/h2&gt;
		&lt;p&gt;&lt;a href=&quot;/&quot;&gt;456 Berea Street Home&lt;/a&gt; | &lt;a href=&quot;/lab/developing_with_web_standards/csslayout/2-col/&quot;&gt;Simple 2 column CSS layout&lt;/a&gt; | &lt;a href=&quot;http://www.456bereastreet.com/lab/developing_with_web_standards/&quot;&gt;Developing with web standards index&lt;/a&gt;&lt;/p&gt;
		&lt;p&gt;Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Mauris vel magna. Mauris risus nunc, tristique varius, gravida in, lacinia vel, elit. Nam ornare, felis non faucibus molestie, nulla augue adipiscing mauris, a nonummy diam ligula ut risus. Praesent varius. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.&lt;/p&gt;
		&lt;p&gt;Nulla a lacus. Nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce pulvinar lobortis purus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec semper ipsum et urna. Ut consequat neque vitae felis. Suspendisse dapibus, magna quis pulvinar laoreet, dolor neque lacinia arcu, et luctus mi erat vestibulum sem. Mauris faucibus iaculis lacus. Aliquam nec ante in quam sollicitudin congue. Quisque congue egestas elit. Quisque viverra. Donec feugiat elementum est. Etiam vel lorem.&lt;/p&gt;
		&lt;p&gt;Aenean tempor. Mauris tortor quam, elementum eu, convallis a, semper quis, purus. Cras at tortor in purus tincidunt tristique. In hac habitasse platea dictumst. Ut eu lectus eu metus molestie iaculis. In ornare. Donec at enim vel erat tempor congue. Nullam varius. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla feugiat hendrerit risus. Integer enim velit, gravida id, sollicitudin at, consequat sit amet, leo. Fusce imperdiet condimentum velit. Phasellus nonummy interdum est. Pellentesque quam.&lt;/p&gt;
		&lt;h3&gt;Consectetuer adipiscing elit&lt;/h3&gt;
		&lt;p&gt;Nulla dictum. Praesent turpis libero, pretium in, pretium ac, malesuada sed, ligula. Sed a urna eu ipsum luctus faucibus. Curabitur fringilla. Suspendisse sit amet quam. Sed vel pede id libero luctus fermentum. Vestibulum volutpat tempor lectus. Vivamus convallis tempus ante. Nullam adipiscing dui blandit ipsum. Nullam convallis lacus ut quam. Mauris semper elit at ante. Vivamus tristique. Pellentesque pharetra ante at pede. In ultrices arcu vitae purus. In rutrum, erat at mollis consequat, leo massa consequat libero, ac vestibulum libero tellus sed risus. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.&lt;/p&gt;
		&lt;p&gt;Maecenas eu velit nec magna venenatis consequat. In neque. Vivamus pellentesque, lacus eu aliquet semper, lorem metus rhoncus metus, a ornare orci ante a diam. Nunc sem nisl, aliquet quis, elementum nec, imperdiet in, wisi. Proin in lorem. Etiam molestie diam eget ante. Morbi quis tortor id lacus mollis venenatis. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam vel orci sit amet tellus mollis eleifend. Donec urna diam, viverra eget, ultricies gravida, ultrices eu, erat. Proin vel arcu. Sed diam. Cras hendrerit arcu sed augue. Sed justo felis, luctus a, accumsan in, tincidunt facilisis, libero. Phasellus eu eros.&lt;/p&gt;
	&lt;/div&gt;
&lt;?php include('sidebar.php');?&gt;
</pre>
<p> Then when creating a new file, simple use the template and change the content in the main div to the new content. When you want to add a link to that page you can add it in sidebar.php or top-menu.php</p>
<h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://teamtutorials.com/web-development-tutorials/using-jquery-to-reorder-a-list-and-update-a-database" title="Using jQuery to Reorder a List and Update a Database">Using jQuery to Reorder a List and Update a Database</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/installing-code-editor" title="Installing Code Editor">Installing Code Editor</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/how-to-return-mysql-results-to-a-table" title="How to Return MySQL Results to a Table">How to Return MySQL Results to a Table</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/hide-and-show-a-div-using-javascript" title="Hide and Show a Div Using Javascript">Hide and Show a Div Using Javascript</a></li><li><a href="http://teamtutorials.com/web-development-tutorials/styling-html-tables-with-tablecloth" title="Styling HTML Tables with TableCloth">Styling HTML Tables with TableCloth</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://teamtutorials.com/web-development-tutorials/simple-php-website-templates/feed</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
	</channel>
</rss>
