<?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"
	>

<channel>
	<title>The Rough Guide to PHP</title>
	<atom:link href="http://www.roughguidetophp.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.roughguidetophp.com</link>
	<description>An introductory tutorial to the world of PHP. Some more advanced subjects too</description>
	<pubDate>Mon, 23 Mar 2009 17:43:59 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.6</generator>
	<language>en</language>
			<item>
		<title>Combining PHP with HTML</title>
		<link>http://www.roughguidetophp.com/adding-php-to-html-files/</link>
		<comments>http://www.roughguidetophp.com/adding-php-to-html-files/#comments</comments>
		<pubDate>Tue, 30 Nov 1999 00:00:00 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[
Now it&#8217;s time to get down to the real task at hand - actually creating a working web-page using PHP. In this tutorial, I&#8217;ll show you how to create a simple web-page to demonstrate how to add a little bit of dynamic jazz to an otherwise static site.

Mixing PHP with HTML
I&#8217;m assuming, for this tutorial, [...]]]></description>
			<content:encoded><![CDATA[<p><!--pagetitle:Mixing PHP With HTML--></p>
<p>Now it&#8217;s time to get down to the real task at hand - actually creating a working web-page using PHP. In this tutorial, I&#8217;ll show you how to create a simple web-page to demonstrate how to add a little bit of dynamic jazz to an otherwise static site.</p>
<p><a name='Mixing PHP with HTML'></a><br />
<h3>Mixing PHP with HTML</h3>
<p>I&#8217;m assuming, for this tutorial, and throughout the rest of the tutorials, that you have at least a basic knowledge of HTML - enough to be able to use simple tags such as &lt;br/&gt; (newline),  &lt;a&gt;, &lt;form&gt; and so on. If not, why not check out any of the decent HTML tutorials around the web - Google for &#8220;HTML Tutorial&#8221;</p>
<p><a name='HTML PHP is HTML'></a><br />
<h3>HTML PHP is HTML</h3>
<p>One thing to realise here is that an HTML page can function as both an HTML page and as a PHP page. Let me explain:</p>
<p>In the previous tutorial, we saw how a PHP file could be created by using the start and end tags, &lt;?php and ?&gt;. We also saw how these tags could start and stop as often as you wished. Within the context of a standard PHP file, this doesn&#8217;t make much sense. After all, what&#8217;s the point of stopping and starting the PHP code if we&#8217;re just going to be executing more of the same PHP?</p>
<p>The answer lies in the fact that, between those PHP tags, we can output HTML content. Take the following code snippet as an example. This is the full text from a PHP file</p>

<div class="wp_syntax"><div class="code"><pre class="php">A sample PHP <span style="color: #990000;">file</span></pre></div></div>

<p>Run this, and we see the output</p>

<div class="wp_syntax"><div class="code"><pre class="php">A sample PHP <span style="color: #990000;">file</span>
And here is the second line</pre></div></div>

<p>Now, what&#8217;s going on here? You might well have guessed by now, the &#8220;echo&#8221; command is used to output data to the screen. But there&#8217;s no echo command on the first line, so how is this text appearing? And more importantly, you might ask, where&#8217;s the semicolon? I did say in an earlier tutorial that any PHP code without a semicolon at the end of each statement will fail. But the important thing to note here is that on line 1, before the &lt;?php tag, that&#8217;s not PHP code</p>
<p>Huh? What?</p>
<p>PHP files can contain both static text and PHP code, the important thing to realise is that, whenever the code is between the &lt;?php and ?&gt; tags, it will be executed as PHP code</p>
<p>The next page will go into a little more detail</p>
]]></content:encoded>
			<wfw:commentRss>http://www.roughguidetophp.com/adding-php-to-html-files/feed/</wfw:commentRss>
		</item>
		<item>
		<title>An introduction to MySQL with PHP</title>
		<link>http://www.roughguidetophp.com/an-introduction-to-mysql-with-php/</link>
		<comments>http://www.roughguidetophp.com/an-introduction-to-mysql-with-php/#comments</comments>
		<pubDate>Tue, 30 Nov 1999 00:00:00 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[

What is MySQL?
If you&#8217;re reading this tutorial, there&#8217;s a good chance you&#8217;ve already gained a reasonable familiarity with PHP programming, and can piece together a simple application with a few lines of code. If not, why not head on over to the PHP Tutorial section for a quick refresher course?
If you have attained a reasonable [...]]]></description>
			<content:encoded><![CDATA[<p><!--pagetitle:What is MySQL? What can I do with it?--></p>
<p><a name='What is MySQL?'></a><br />
<h3>What is MySQL?</h3>
<p>If you&#8217;re reading this tutorial, there&#8217;s a good chance you&#8217;ve already gained a reasonable familiarity with PHP programming, and can piece together a simple application with a few lines of code. If not, why not head on over to the <a href="/category/php/">PHP Tutorial</a> section for a quick refresher course?</p>
<p>If you have attained a reasonable understanding of PHP, you&#8217;ll be aware of the great potential PHP has for building web-based applications and interactive websites to allow users to add content or contribute to discussions. This interactivity is a major component of many such sites, and the ability of these sites to store and manipulate user data plays a vital role in their success.</p>
<p>One of the most common technologies used on the internet to store large quantities of data for future retrieval and display is the database system MySQL. MySQL is an example of a database management system (DBMS) which, in laymans terms, means that it has the ability to store and retrieve large amounts of data for whatever use the user sees fit. In our case, for display in our dynamic websites and applications.</p>
<p><a name='Data Storage for the Masses'></a><br />
<h3>Data Storage for the Masses</h3>
<p>Data storage is a hot topic on the internet today. If you&#8217;ve used Google&#8217;s GMail application for email, you&#8217;ll have seen that they currently offer roughly 7 Gigabytes of storage per person. That&#8217;s a lot of space! Other sites, such as Flickr for photography, and Facebook for social networking and chat also require a lot of storage space to allow their users to keep track of the vast amounts of information they upload.</p>
<p>You might be surprised to know, but the same technology that powers these sites, and keeps them running with millions and millions of hits is the very same technology I&#8217;m going to introduce you to here. Yep, that&#8217;s right - MySQL is capable enough to support multi-million user websites while at the same time being simple enough to pick up and learn the basics in a short timeframe. What&#8217;s more, it&#8217;s completely free! Thanks to the wonders of Open Source software, this powerful database tool is available for anyone to download and start using right away. Maybe one day when you become a top notch developer, you could contribute something back to this fantastic community of community-created software!</p>
<p><a name='MySQL with PHP'></a><br />
<h3>MySQL with PHP</h3>
<p>PHP is a scripting language, used to generate web-pages and process information. MySQL is a data storage application, and is used to keep track of vast quantities of data. When you put the two together, you gain the power of PHP to display and alter the data stored within MySQL in whatever way you desire.</p>
<p>PHP and MySQL are two completely seperate applications. One can happily exist without the other, and it&#8217;s even possible to use other programming languages with MySQL (Perl, Java etc.), as well as other database systems with PHP (PostgreSql and others) but the combination of PHP with MySQL is one of the most widely used, and many of the most popular content management systems (such as Wordpress, Drupal and Joomla) cannot function without them.</p>
<p>The link between PHP and MySQL comes with the use of a database extension to allow PHP to access and modify the data held within the database through the use of special PHP function calls, such as mysql_query() to run a specific query on the database, and mysql_connect() to establish a connection to the database at runtime.</p>
<p>The proper usage of these functions, and more detail about other MySQL extension functions will be outlined in later sections in this tutorial.</p>
<p>Please note that all these tutorials assume that you&#8217;re using the combination of PHP with MySQL. You&#8217;ll still be able to get something out of it if you&#8217;re not using PHP, since the majority of the tutorial relies on only a few simple PHP functions, and these will usually have similar equivalents in whatever other language you&#8217;re using</p>
]]></content:encoded>
			<wfw:commentRss>http://www.roughguidetophp.com/an-introduction-to-mysql-with-php/feed/</wfw:commentRss>
		</item>
		<item>
		<title>An Introduction to PHP</title>
		<link>http://www.roughguidetophp.com/an-introduction-to-php/</link>
		<comments>http://www.roughguidetophp.com/an-introduction-to-php/#comments</comments>
		<pubDate>Tue, 30 Nov 1999 00:00:00 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[

Website design with PHP
It&#8217;s quite likely you&#8217;ve reached this page because you&#8217;re interested in learning how to build your first website with PHP, or modify your existing website to make use of PHP. It&#8217;s also quite likely, if you&#8217;re just starting out with PHP, or programming in general, that you won&#8217;t really know what PHP [...]]]></description>
			<content:encoded><![CDATA[<p><!--pagetitle:Introduction--></p>
<p><a name='Website design with PHP'></a><br />
<h3>Website design with PHP</h3>
<p>It&#8217;s quite likely you&#8217;ve reached this page because you&#8217;re interested in learning how to build your first website with PHP, or modify your existing website to make use of PHP. It&#8217;s also quite likely, if you&#8217;re just starting out with PHP, or programming in general, that you won&#8217;t really know what PHP is exactly, or what it does.</p>
<p>PHP is one of the most widely used technologies for building websites. Alongside the database management system MySQL, it powers some of the most popular and heavily visited sites. The role of PHP in these websites is to construct the pages of text and images you see when you navigate these sites, and it can also be used for even more complex operations behind the scenes. PHP can dynamically construct pages based on user input, so that you don&#8217;t need to offer visitors static pages of text, but can instead provide them with information based on their specific requirements.</p>
<p>A user might, for example, select from a drop-down list of items in a shop, and be presented with a detailed description of the selected product, or fill in an email form to contact you directly about a service, bypassing the need to provide your email address on a public website.</p>
<p>If you&#8217;re already familiar with PHP, you may already have covered most of the topics in the first part of this tutorial. We will cover some of the fundamentals of programming, including for loops, if&#8230;else statements and more. Although some people may be well versed in the use of these programming methods, there may still be information of value. Near the end of each section I will look at each subject in more detail, and there may even be one or two nuggets of information which even the more experienced PHP developer will find useful!</p>
<p>This tutorial won&#8217;t aim to cover everything though, and doesn&#8217;t aim to replace the more comprehensive PHP references out there - including PHP&#8217;s own, extremely useful, online library available through <a href="http://www.php.net/manual/en/index.php">php.net</a></p>
<p><a name='What is PHP?'></a><br />
<h3>What is PHP?</h3>
<p>It is said that the acronym PHP is recursive, and stands for &#8220;PHP: Hypertext Preprocessor&#8221;, which would no doubt cause some headaches if you attempted to write it out in full. A more sensible explanation is that it stands for &#8220;Personal Home Page&#8221;, originally from a piece of software developed by Danish programmer Rasmus Lerdorf to maintain his own personal homepage.</p>
<p>These days, PHP is still used to maintain personal homepages. Also business pages, online directories, online shops&#8230; the list goes on. It is an extremely versatile language and, while its critics may say it lacks the langauge processing capabilities of Perl, say, or the complexities of C/C++, there&#8217;s no arguing that it is a very capable language for use in creating the underlying code and structure of a great number of websites</p>
<p><img class="size-full wp-image-156" title="whatisphp" src="/wp-content/uploads/2008/08/whatisphp.jpg" alt="" width="440" height="182" />
<p class="wp-caption-text">How PHP Works. Roughly</p>
<p>The basic idea behind PHP is outlined in the image above. PHP code is stored within PHP Files [1], which are then passed through a PHP Parser [2] that then generates the code necessary to display the webpage [3] you see when you visit a specific URL, like http://www.mywebsite.com/index.php</p>
]]></content:encoded>
			<wfw:commentRss>http://www.roughguidetophp.com/an-introduction-to-php/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Arrays in PHP</title>
		<link>http://www.roughguidetophp.com/arrays-in-php/</link>
		<comments>http://www.roughguidetophp.com/arrays-in-php/#comments</comments>
		<pubDate>Tue, 30 Nov 1999 00:00:00 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[

Arrays
There are times in programming where you need to keep track of many variables at once. Maybe the current time of day, the number of items in a package or the name of a certain product. These variables may all be very similar too though, you might, for example, need to keep track of the [...]]]></description>
			<content:encoded><![CDATA[<p><!--pagetitle:Introduction to Arrays--></p>
<p><a name='Arrays'></a><br />
<h3>Arrays</h3>
<p>There are times in programming where you need to keep track of many variables at once. Maybe the current time of day, the number of items in a package or the name of a certain product. These variables may all be very similar too though, you might, for example, need to keep track of the names of all employees in a company, or the number of items inside each of a large number of packages.  Arrays can be used to keep track of these multiple values from within one variable.</p>
<p>Arrays are a special type of data structure in PHP. They are used to hold multiple values, in a way which allows the values held within to be re-arranged, searched or sorted. Values can also be removed or added easily. Arrays are especially useful when you&#8217;re dealing with lists of items, or collections of values that need to be sorted into ascending or descending order.</p>
<p><a name='Creating and manipulating arrays'></a><br />
<h3>Creating and manipulating arrays</h3>
<p>An array is initialised using the language construct array(), and is assigned to a PHP variable name, in exactly the same way as other scalar variables [reference scalar in previous tut]. Arrays can contain any number of values, each of which can be any of the PHP data types. Here is an example of a simple array</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$array</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;two&quot;</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">3.0</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;four&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This will initialise the variable $array as an array containing the values 1, &#8220;two&#8221;, 3.0 and &#8220;four&#8221;.</p>
<p>An array like this is known as a Non-associative array because the values are not associated with any specific keys but are instead just numbered numerically, like so&#8230;</p>
<p><img src="/wp-content/uploads/2008/08/array1.jpg" alt="An example of a simple non-associative array" title="array1" width="430" height="187" class="size-full wp-image-192" />
<p class="wp-caption-text">An example of a simple non-associative array</p>
<p><a name='Displaying Arrays'></a><br />
<h3>Displaying Arrays</h3>
<p>Once this array has been initialised, we can check the contents of the array in certain ways</p>
<pre class="php">echo $array;
print_r &#40;$array&#41;;
var_dump&#40;$array&#41;;</pre>
<p>This produces</p>
<pre class="php">Array
Array &#40; &#91;0&#93; =&gt; 1 &#91;1&#93; =&gt; two &#91;2&#93; =&gt; 3 &#91;3&#93; =&gt; four &#41;
array&#40;4&#41; &#123; &#91;0&#93;=&gt; int&#40;1&#41; &#91;1&#93;=&gt; string&#40;3&#41; &quot;two&quot; &#91;2&#93;=&gt; float&#40;3&#41; &#91;3&#93;=&gt; string&#40;4&#41; &quot;four&quot; &#125;</pre>
<p>Echo is not built to handle complex data structures like arrays. Instead we need to turn to our old friend print_r() - but even then, we&#8217;re not getting the full picture. Var_dump() produces the most information about our array, giving us the datatype held in each position of the array.</p>
<p><a name='Associative arrays'></a><br />
<h3>Associative arrays</h3>
<p>Note the numbers in square brackets on lines 2 and 3 in the above example. These numbers correspond to the &#8220;keys&#8221; of each item in the array. Arrays work by assigning each item a &#8220;key-value pair&#8221; by which to reference each position in the array. In the above example, the keys are generated automatically, in sequence according to the order in which the values were entered. We can over-ride this behaviour though, and specify our own keys for each value</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$array</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">4</span> <span style="color: #339933;">=&gt;</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">3</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;two&quot;</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">2</span> <span style="color: #339933;">=&gt;</span> <span style="color: #cc66cc;">3.0</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">1</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;four&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Here, we&#8217;ve assigned the entries in the array to keys in descending numerical order.</p>
<p>Another example is an array containing a list of employee names, and their associated job titles</p>
<p><img src="/wp-content/uploads/2008/08/array2.jpg" alt="" title="array2" width="500" height="217" class="aligncenter size-full wp-image-194" /></p>
<p>Now, you might be asking, what&#8217;s the use of this feature in real code? Well, this gives me a good opportunity to introduce a powerful feature of arrays - sorting.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.roughguidetophp.com/arrays-in-php/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Classes and Object-Oriented Programming in PHP</title>
		<link>http://www.roughguidetophp.com/classes-and-object-oriented-programming-in-php/</link>
		<comments>http://www.roughguidetophp.com/classes-and-object-oriented-programming-in-php/#comments</comments>
		<pubDate>Tue, 30 Nov 1999 00:00:00 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[
So far throughout this tutorial, we&#8217;ve been looking at a method of programming called &#8220;procedural programming&#8221; in which program execution proceeds in a linear fashion, from start to finish and makes use of procedure calls. Procedures, which we&#8217;ve come to know as functions, allow us to execute arbitrary code segments at any point throughout the [...]]]></description>
			<content:encoded><![CDATA[<p><!--pagetitle:Introduction to Classes--><br />
So far throughout this tutorial, we&#8217;ve been looking at a method of programming called &#8220;procedural programming&#8221; in which program execution proceeds in a linear fashion, from start to finish and makes use of procedure calls. Procedures, which we&#8217;ve come to know as functions, allow us to execute arbitrary code segments at any point throughout the script.</p>
<p>Procedural programming has many advantages, mainly the ability to store frequently used code within functions, and to encompass complex algorithms within easy-to-remember function names.</p>
<p>In this tutorial, I&#8217;ll take things a step further, and introduce you to the concept of Classes and Objects in PHP. To put it simply, an Object in the context of programming languages is a data structure which can contain any number of variables and functions all held together under a Class name. This Class can then be created in the normal scope of the code and stored inside a new variable, and multiple copies of this same class can be created. This allows for an even greater level of code encapsulation, allowing more complexity to be accessed from simple commands.</p>
<p>I mentioned that procedural programming allows us to encapsulate code within functions to be re-used as required. Classes take that a step further, allowing us to encapsulate many functions within a class and to create multiple copies of each class.</p>
<p>Note that, when inside a class definition, functions are referred to as methods, and variables are referred to as members - even though we still use the keyword &#8220;function&#8221; to define methods.</p>
<p><a name='Methods : &#8220;Functions defined inside Classes&#8221;'></a><br />
<h3>Methods : &#8220;Functions defined inside Classes&#8221;</h3>
<p>When defining a function within a class, we refer to it as a method, and this method then becomes available to all instances of a class. The following example shows the syntax used to define a class, and also create an instance of the class for use. We will then call the method defined within the class, using this newly created instance</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">Class</span> MyClass <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">function</span> myFunction<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
      <span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;Hello world!&quot;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000033;">$myObject</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyClass<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//create an instance of MyClass called $myObject</span>
<span style="color: #000033;">$myObject</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">myFunction</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  <span style="color: #666666; font-style: italic;">//call the method, myFunction() using the instance</span></pre></div></div>

<p>Lets take a step by step look at what&#8217;s happening here</p>
<p>Line 1 : New classes in PHP are defined by the use of the Class keyword, followed by a user defined name to label the class. Here, we&#8217;re calling our class MyClass. The body of the class is placed between a pair of braces. Class naming convention is the same as for standard variables and function names, and traditionally class names start with an uppercase letter<br />
Lines 2-4 : Within the class, we can define a range of variables and functions. Here, we&#8217;re defining just one function, in this case, the function myFunction, which serves a single purpose - to print &#8220;Hello world!&#8221;<br />
Line 6 : Here&#8217;s where the fun begins! After a class has been created, we can then assign instances of the class to variables. Here, we make use of the &#8220;new&#8221; keyword to create a new copy of the MyClass object. Note the parentheses after MyClass. These aren&#8217;t explicitly required here, but later on in the tutorial, I&#8217;ll show you how you can place values within these to add extra functionality to your class.<br />
Line 7 : by the use of the -> operator we can call functions and access variables within the class object. Here, we are calling the myFunction function. This will produce the now-familiar output</p>

<div class="wp_syntax"><div class="code"><pre class="text">Hello world!</pre></div></div>

<p>Multiple instances of the same class can be created. This way, we can reuse the functionality of the class without needing to worry about redeclaring variables, or functions</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$firstObject</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyClass<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$secondObject</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyClass<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$thirdObject</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyClass<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$firstObject</span> <span style="color: #339933;">-&gt;</span><span style="color: #004000;">myFunction</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$secondObject</span> <span style="color: #339933;">-&gt;</span><span style="color: #004000;">myFunction</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$thirdObject</span> <span style="color: #339933;">-&gt;</span><span style="color: #004000;">myFunction</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Let&#8217;s take a step forwards now and add in some variables, or members into our functions. When defining variables within the body of a class, we refer to these variables as members. Here is an example of another class definition with a couple of members, $a and $b defined within its body.</p>
<p><a name='Members : &#8220;Variables defined inside Classes&#8221;'></a><br />
<h3>Members : &#8220;Variables defined inside Classes&#8221;</h3>
<pre class="php">Class MyClass &#123;
  public $a = 5;
  public $b = 10;
&nbsp;
  function showValues&#40;&#41;&#123;
    echo &quot;a equals $this-&gt;a&quot;;
    echo &quot; and b equals $this-&gt;b&quot;;
  &#125;
&#125;
$class = new MyClass;
$class-&gt;showValues&#40;&#41;;
echo &quot;a plus b = &quot;.&#40;$class-&gt;a + $class-&gt;b&#41;;</pre>

<div class="wp_syntax"><div class="code"><pre class="text">a equals 5 and b equals 10
a plus b = 15</pre></div></div>

<p>Here, you&#8217;ll see much that is familiar from the previous example. We define a class using the &#8220;Class&#8221; keyword, and inside the class is a function, or method showValues(). But, we&#8217;ve got a couple of new things here that need some explaining!</p>
<p>Lines 2 and 3 : Here, you can see a couple of members $a and $b being defined, in much the same way as we&#8217;d define variables within the normal scope of a script, except when defining members inside a class, we must use the public keyword. There are exceptions to this rule though, and they will be explained shortly. Note that it is also acceptable to define members by using the keyword var e.g. var $a = 5; although this usage is a remnant from earlier versions of PHP and is only supported for compatibility reasons. It is better to use public<br />
Lines 6 and 7 : Now that we have the variables $a and $b defined within the body of the class, we can use these values from within functions. Here, you&#8217;ll see another mysterious variable - $this. $this is a very special variable in PHP. When inside a class, or object, $this allows you to refer to the class from within itself. Notice how, when calling a class method from outwith the class definition we use the notation $class-&gt;functionName()? When we&#8217;re running code from inside the class itself, we can do the same thing, but instead of using the name of the class, we simply use $this. This way we can refer to the class object without needing to know the specific variable name the class has been assigned to.In this case, we&#8217;re working with the values of $a and $b from inside the method by referring to them with $this-&gt;a and $this-&gt;b<br />
Line 12 : Here we are accessing the values of $a and $b directly. You can see from this example how it&#8217;s much cleaner, and compact to use methods from within the class to access variables in this way, since it allows for greater code portability. This code can be improved like so,</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">Class</span> MyClass <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000033;">$a</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">5</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000033;">$b</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">10</span><span style="color: #339933;">;</span>
 
  <span style="color: #000000; font-weight: bold;">function</span> addValues<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #0000ff;">&quot;a plus b = &quot;</span><span style="color: #339933;">.</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">a</span> <span style="color: #339933;">+</span> <span style="color: #000033;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">b</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000033;">$class</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyClass<span style="color: #339933;">;</span>
<span style="color: #990000;">echo</span> <span style="color: #000033;">$class</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">addValues</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Confused? Yes, don&#8217;t worry, it can be a little overwhelming at first, but the thing to remember about Object Oriented Programming is that it uses lots of the same principles you&#8217;ve been using already, but with a little twist. It&#8217;s really about changing the way you think about coding, into a more packaged, compartmentalised view of things.</p>
<p>In the next section, we&#8217;re going to take a look at how we can control access to the members and methods contained within a class</p>
]]></content:encoded>
			<wfw:commentRss>http://www.roughguidetophp.com/classes-and-object-oriented-programming-in-php/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Conditional Statements in PHP</title>
		<link>http://www.roughguidetophp.com/conditional-statements-in-php/</link>
		<comments>http://www.roughguidetophp.com/conditional-statements-in-php/#comments</comments>
		<pubDate>Tue, 30 Nov 1999 00:00:00 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[
Conditional statements are used in PHP (and in any other programming language) when the programmer wishes to place a branch in the code, where a specific result will occur if, and only if, a set of conditions is matched. A real world example might be
I will go to the cinema if I have $15 or [...]]]></description>
			<content:encoded><![CDATA[<p><!--pagetitle:An introduction to If, Else, Switch and Elseif--><br />
Conditional statements are used in PHP (and in any other programming language) when the programmer wishes to place a branch in the code, where a specific result will occur if, and only if, a set of conditions is matched. A real world example might be</p>
<p>I will go to the cinema if I have $15 or more to spend tonight</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$amount</span>  <span style="color: #339933;">&gt;=</span> <span style="color: #cc66cc;">15</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;I'm going to the cinema&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>
But, what would you do if you didn&#8217;t go to the cinema? There&#8217;s usually an alternative&#8230;</p>
<p>I will go to the cinema if I have $15 or more. Otherwise, I&#8217;ll just stay in and watch TV</p>
<p>This would be represented in PHP as</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$amount</span>  <span style="color: #339933;">&gt;=</span> <span style="color: #cc66cc;">15</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;I'm going to the cinema&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;I'm a bit skint. I think I'll just stay in and watch Friends re-runs again&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The first line sets up the proposition, &#8220;What&#8217;s the value of $amount?&#8221; or, &#8220;How much money have I got?&#8221;. The curly brackets (or braces) are the containers for each of the outcomes (this is an important syntactical feature of PHP).</p>
<p>What we&#8217;re saying here is that the echo statement contained within the first pair of braces (line 2) will be executed if the value of $amount is greater than or equal to (>=) 15</p>
<p>The statement within the second set of braces (line 4) is executed when $amount is less than 15. The &#8220;else&#8221; operator tells PHP that we want one or the other - not both - dependant on the outcome of the &#8220;if&#8221; statement</p>
<p><a name='True &#038; False'></a><br />
<h3>True &#038; False</h3>
<p>PHP, much like any other language, uses the two boolean values TRUE and FALSE to represent the outcome of logical expressions. The result of a statement like &#8220;$amount >= 15&#8243; will equal TRUE if the variable $amount holds a numerical value which is greater than, or equal to 15 and FALSE otherwise. Here are some other examples of boolean expressions</p>

<div class="wp_syntax"><div class="code"><pre class="php">  <span style="color: #cc66cc;">5</span> <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">3</span> <span style="color: #666666; font-style: italic;">//TRUE, 5 is greater than 3</span>
  <span style="color: #cc66cc;">3</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">4</span> <span style="color: #666666; font-style: italic;">//TRUE, 4 is indeed greater than or equal to 4</span>
  <span style="color: #cc66cc;">5</span> <span style="color: #339933;">!=</span> <span style="color: #cc66cc;">3</span> <span style="color: #666666; font-style: italic;">//TRUE, 5 is not equal to (!=) 3</span>
  <span style="color: #cc66cc;">3</span> <span style="color: #339933;">!=</span> <span style="color: #cc66cc;">3</span> <span style="color: #666666; font-style: italic;">//FALSE, 3 is equal to 3 - the operand &quot;!=&quot; fails here</span>
  <span style="color: #cc66cc;">5</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">5</span> <span style="color: #666666; font-style: italic;">//TRUE, 5 does indeed equal 5</span></pre></div></div>

<p>These are fairly banal examples. I can&#8217;t imagine anyone would get excited about writing a program to prove that 5 equals 5!</p>
<p><a name='Equality operator (==) &#038; Assignment operator (=)'></a><br />
<h3>Equality operator (==) &#038; Assignment operator (=)</h3>
<p>An important thing to note about the last example is the use of equality operator (==) This is not the same as the assignment operator (=) == is used to check if two values are equal, whereas = is used to assign a specific value to a variable. i.e.</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$x</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">5</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// $x now equals 5</span>
<span style="color: #000033;">$x</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">7</span><span style="color: #339933;">;</span>  <span style="color: #666666; font-style: italic;">/* 7 doesn't get assigned to $x
 instead, the whole expression equates to false
 since $x doesn't equal 7 */</span></pre></div></div>

<p>We can see this more clearly by looking at the value of each expression as a whole using var_dump()</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #990000;">var_dump</span> <span style="color: #009900;">&#40;</span><span style="color: #000033;">$x</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">5</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">/* int(5) */</span>
<span style="color: #990000;">var_dump</span> <span style="color: #009900;">&#40;</span><span style="color: #000033;">$x</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">7</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  <span style="color: #666666; font-style: italic;">/*  bool(false)  */</span></pre></div></div>

<p><a name='AND &#038; OR'></a><br />
<h3>AND &#038; OR</h3>
<p>Sometimes you want to base the outcome of a situation on more than one variable, you wish to know, for example, that two certain conditions will be fulfilled before deciding on a choice of action. Expanding on our cinema example from earlier -</p>
<p>If I have $15 or more AND it is not raining, I&#8217;ll go to the cinema. Otherwise I&#8217;ll stay in and watch TV</p>
<p>becomes&#8230;</p>
<pre class="php">if&#40;$amount &gt;= 15.00 &amp;&amp; !$raining&#41;&#123;
  echo &quot;I really want to see the new Indiana Jones film&quot;;
&#125; else &#123;
  echo &quot;It's too wet out, and the episode of Friends where they play 'Fireball' is on&quot;;
&#125;</pre>
<p>Here, we are using the operator &#8220;&#038;&#038;&#8221; to represent the expression &#8220;and&#8221; - similarly, we can use the operator &#8220;||&#8221; to represent &#8220;or&#8221;.</p>
<p>This statement is based on two things - firstly, the same condition as before - how much money have I got?  Secondly, the condition &#8220;!$raining&#8221;. The exclamation mark before $raining is means that !$raining will equate to TRUE only if $raining equals FALSE. Confusing? Yes, it is a little bit to begin with, but dealing with logical expressions usually can be!</p>
<p>Think of it this way - it can be rewritten as</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$amount</span> <span style="color: #339933;">&gt;=</span> <span style="color: #cc66cc;">15.00</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #000033;">$raining</span> <span style="color: #339933;">==</span> <span style="color: #000000; font-weight: bold;">FALSE</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span></pre></div></div>

<p>Which makes more sense. You may encounter quite a few situations like this in PHP, where things are written in a specific shorthand that somewhat obscures the meaning, but once you get the hang of it you find it quicker and simpler to use the shorthand version. Take the following code snippet&#8230;</p>
<p><a name='Elseif'></a><br />
<h3>Elseif</h3>
<p>Sometimes it might be the case that there aren&#8217;t just two potential outcomes to a situation. Indeed, as with most scenarios in life, there are many more. Consider yet another modifcation to the above scenario.</p>
<p>I&#8217;m going to the cinema if it&#8217;s not raining, and I have $15 or more. If it is raining, I&#8217;ll stay in and watch TV. Otherwise, if it isn&#8217;t raining, but I have less than $15, I&#8217;ll go and visit my friends</p>
<p>Here, we have three unique outcomes - going to the cinema, staying in, or visiting friends. We can work this out with logic by introducing another choice in our if statement, as follows</p>
<pre class="php">if&#40;$amount &gt;= 15.00 &amp;&amp; !$raining&#41;&#123;
  echo &quot;Let's go to the cinema&quot;;
&#125; elseif &#40;$amount &lt; 15.00 &amp;&amp; !$raining&#41;&#123;
  echo &quot;I'm going to visit friends&quot;;
&#125; else if&#40;$amount &lt; 15.00 &amp;&amp; $raining == TRUE&#41; &#123;
  echo &quot;I think I'll just stay in tonight&quot;;
&#125;</pre>
<p>Notice though, in the final case, we&#8217;re doing checks for logical conditions that aren&#8217;t actually required, given that we can reason, through logical deduction, that if it&#8217;s raining, neither of the first cases will match, so the check for $raining == TRUE is redundant. Likewise, because we know that the value of $amount isn&#8217;t relevant either, we can safely ignore that too. A more compact way of writing the above code would be</p>
<pre class="php">if&#40;$amount &gt;= 15.00 &amp;&amp; !$raining&#41;&#123;
  echo &quot;Let's go to the cinema&quot;;
&#125; elseif &#40;$amount &lt; 15.00 &amp;&amp; !$raining&#41;&#123;
  echo &quot;I'm going to visit friends&quot;;
&#125; else &#123;
  echo &quot;I think I'll just stay in tonight&quot;;
&#125;</pre>
<p>Usually, for the final condition in an if&#8230;elseif&#8230;else statement, we have already checked for all the relevant conditions we&#8217;re interested in, and this final &#8220;else&#8221; is simply the &#8220;default case&#8221;</p>
<p><a name='Conditional Shorthand using ? and :'></a><br />
<h3>Conditional Shorthand using ? and :</h3>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #990000;">echo</span> <span style="color: #009900;">&#40;</span><span style="color: #000033;">$amount</span> <span style="color: #339933;">&gt;=</span><span style="color: #cc66cc;">15</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #339933;">!</span><span style="color: #000033;">$raining</span><span style="color: #009900;">&#41;</span>?<span style="color: #0000ff;">&quot;I'm going to the cinema&quot;</span><span style="color: #339933;">:</span><span style="color: #0000ff;">&quot;I'm going to stay in&quot;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Now what on earth is all that about?  Well, it&#8217;s exactly the same expression as before - only written in an even more shorthand way.  This time, we&#8217;re using the conditional operators ? and : to express our situation.</p>
<p>An interesting way to view this is to think of the ? in the statement above in exactly the same way as you would view it in a normal sentence.  Let&#8217;s reword our thoughts about going to the movies&#8230;</p>
<p>Is it dry outside, and do I have more than $15? If so, then I&#8217;ll head out. If not, then I&#8217;ll stay in</p>
<p>We&#8217;re asking a question here - the same question in PHP form reads..</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$amount</span> <span style="color: #339933;">&gt;=</span><span style="color: #cc66cc;">15</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #339933;">!</span><span style="color: #000033;">$raining</span>?<span style="color: #666666; font-style: italic;">/* if so */</span><span style="color: #0000ff;">&quot;I'm not going to the cinema&quot;</span><span style="color: #339933;">:</span><span style="color: #666666; font-style: italic;">/* otherwise */</span><span style="color: #0000ff;">&quot;I am going to the cinema&quot;</span><span style="color: #339933;">;</span></pre></div></div>

<p>(I added in some extra wording in comments to make it clearer - that might not be fully accepted as valid PHP code though)</p>
<p>Here, we&#8217;re using the colon (:) to mean &#8220;Otherwise&#8221;, so the use of the ? and : operators basically amounts to</p>

<div class="wp_syntax"><div class="code"><pre class="text">  (statement which equals either TRUE or FALSE)?Do this if it's true:Do this if it's false;</pre></div></div>

<p>If you think about it, you can also imagine how you could place other conditional statements within the expressions to be evaluated in either case, to produce even more complex scenarios</p>
<p>Let&#8217;s expand again on our cinema example</p>
<p>I&#8217;m going to the cinema if it&#8217;s not raining, and I have $15 or more. Otherwise I&#8217;ll stay in and watch TV. But, if my friends call me up to go along, I&#8217;ll head anyway</p>
<pre class="php">if&#40;&#40;$amount &gt;= 15.00 &amp;&amp; !$raining&#41; || $friends_have_called == true&#41;&#123;
  echo &quot;Let's go to the cinema&quot;;
&#125; else &#123;
  echo &quot;Nah, let's not bother&quot;;
&#125;</pre>
<p>Here, the conditional statement in line 1 has expanded to include an &#8220;or&#8221; (||) condition - either, it&#8217;s not raining and I have enough money, or, my friends have called. If my friends have called, it doesn&#8217;t matter about the first expression.</p>
<p>Note as well, that the first condition has been placed in brackets, instead of writing</p>
<pre class="php">if&#40;$amount &gt;= 15.00 &amp;&amp; !$raining || $friends_have_called == true&#41;&#123;</pre>
<p>Which is prone to misinterpretation (That could be saying &#8220;If I have more than $15, and it&#8217;s either not raining or my friends have called&#8230;&#8221;) There is a feature of programming called operator precedence which defines which operator is considered first, but when in doubt, always use brackets to make your statements clearer - it helps when other people look at your code too</p>
<p><a name='Switch Statements'></a><br />
<h3>Switch Statements</h3>
<p>One other way of providing a conditional response to an expression is to use the switch() function. This function is especially useful when we expect one of a fixed number of outcomes to occur, and we wish to compare a specific variable to each, to find out which value has occured.</p>
<p>The switch() function also uses the keywords case, default and break, and the exact purpose of these can be seen in the example below.</p>
<pre class="php">$i = 2;
switch&#40;$i&#41;&#123;
  case 2:
    echo &quot;i is equal to 2&quot;;
    break;
  case 3:
    echo &quot;i is three&quot;;
    break;
  case 1:
    echo &quot;i is only one here&quot;;
    break;
  default:
    echo &quot;i is neither 1, 2 or 3&quot;;
    break;
&#125;</pre>
<p>The above code will output</p>

<div class="wp_syntax"><div class="code"><pre class="text">i is equal to 2</pre></div></div>

<p>Here, we are using the case keyword to declare which of the outcomes 1, 2 or 3 we wish to deal with in each case. The switch statement itself is encased within a pair of braces (lines 2 &#038; 15) and each case statement is simply defined by whatever code appears between the colon (:) and the break; statement. </p>
<p>The final case is named &#8220;default&#8221;, and this is the case which occurs when none of the previous cases is matched. The usage here is similar to the last sentence I wrote in the section above about &#8220;elseif&#8221; - the last default case is usually the one that requires no extra conditions to be matched.</p>
<p>This switch statement above is identical in functionality to the series of if statements:</p>
<pre class="php">$i = 2;
if&#40;$i==2&#41;&#123;
  echo &quot;i is equal to 2&quot;;
&#125; elseif &#40;$i==3&#41; &#123;
  echo &quot;i is three&quot;;
&#125; elseif &#40;$i==1&#41; &#123;
  echo &quot;i is only one here&quot;;
&#125; else &#123;
  echo &quot;i is neither 1, 2 or 3&quot;;
&#125;</pre>
<p>But the switch statement is arguably more compact, and a bit simpler to code than the equivalent code using &#8220;if&#8221;</p>
<p><a name='Footnote : An alternate syntax for If&#8230;else statements'></a><br />
<h3>Footnote : An alternate syntax for If&#8230;else statements</h3>
<p>if&#8230;else statements can also be written using the following syntax</p>

<div class="wp_syntax"><div class="code"><pre class="php">&nbsp;</pre></div></div>

<p>Note that, in the second code example, there is no need for any braces round each of the results. All the code to be executed based on the logic expression is contained between each of the if:, elseif: and else: statements</p>
<p>Note as well, it&#8217;s vitally important to include the &#8220;endif;&#8221; statement, to replace the final closing brace.</p>
<p>Switch statements can also be written as</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #b1b100;">switch</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$i</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span>
  <span style="color: #b1b100;">case</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">:</span>
    <span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;one&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">default</span><span style="color: #339933;">:</span>
    <span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;not one&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">endswitch</span><span style="color: #339933;">;</span></pre></div></div>

<p>And similar syntactical differences can be applied to while loops, for loops and foreach loops</p>
<p>This way of writing if statements can be useful, and slightly tidier, but is slightly more prone to errors, especially when nesting if statements, and can sometimes produce erratic results</p>
]]></content:encoded>
			<wfw:commentRss>http://www.roughguidetophp.com/conditional-statements-in-php/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Functions in PHP</title>
		<link>http://www.roughguidetophp.com/functions-in-php/</link>
		<comments>http://www.roughguidetophp.com/functions-in-php/#comments</comments>
		<pubDate>Tue, 30 Nov 1999 00:00:00 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[
Functions are arguably one of the most useful features of PHP. They allow a programmer to encapsulate sections of code within a structure which can then be executed from anywhere else in the program flow. Functions are instantiated by use of the function keyword, followed by the user-defined function name including a list of parameters [...]]]></description>
			<content:encoded><![CDATA[<p><!--pagetitle:An Introduction to Functions--><br />
Functions are arguably one of the most useful features of PHP. They allow a programmer to encapsulate sections of code within a structure which can then be executed from anywhere else in the program flow. Functions are instantiated by use of the function keyword, followed by the user-defined function name including a list of parameters between the paretheses (but we&#8217;ll worry about that in a moment) and the body of the function is contained between braces.</p>
<p>Just as when defining variables, specific naming conventions must be adhered to. A function name can contain letters, numbers and underscores, and must not start with a number. They are also, like variables, case-sensitive. A (very simple) example:</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">function</span> my_function<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;Hello world&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #000033;">$a</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">5</span><span style="color: #339933;">;</span>
  <span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;The value of $a is $a&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
my_function<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="php">Hello world
The value of <span style="color: #000033;">$a</span> is <span style="color: #cc66cc;">5</span></pre></div></div>

<p>Line 1 : The definition of the function. This declares that you, the programmer, have decided to create a function for use called &#8220;my_function&#8221;. The empty brackets () will be filled in later, but they are important and you cannot leave them out.<br />
Lines 2-4 : Inside the braces you can place whatever code you desire<br />
Line 6 : This is a function call and lets PHP know that we want to execute the function at this point. This differs from the function declaration in that we are not using the function keyword to create a function. This function call can occur anywhere within the code, as long as it occurs after the function has been declared</p>
]]></content:encoded>
			<wfw:commentRss>http://www.roughguidetophp.com/functions-in-php/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Loops in PHP : While and For</title>
		<link>http://www.roughguidetophp.com/loops-in-php-while-and-for/</link>
		<comments>http://www.roughguidetophp.com/loops-in-php-while-and-for/#comments</comments>
		<pubDate>Tue, 30 Nov 1999 00:00:00 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[

Introduction to Loops
Loops in PHP are very useful when you need to perform repetitions of the same code over and over again, or when you need to ensure that you iterate through all possible values of an array, for example. They come in a few different flavours, the most common being &#8220;for&#8221; loops and &#8220;while&#8221; [...]]]></description>
			<content:encoded><![CDATA[<p><!--pagetitle:An introduction to For and Foreach Loops in PHP--></p>
<p><a name='Introduction to Loops'></a><br />
<h3>Introduction to Loops</h3>
<p>Loops in PHP are very useful when you need to perform repetitions of the same code over and over again, or when you need to ensure that you iterate through all possible values of an array, for example. They come in a few different flavours, the most common being &#8220;for&#8221; loops and &#8220;while&#8221; loops. There are a few other more obscure ways to create loops, and I&#8217;ll cover them at the end, in the extended section.</p>
<p>The three types of loop I will cover in this section are For loops, While loops and Foreach loops</p>
<p><a name='While loops'></a><br />
<h3>While loops</h3>
<p>While loops are the simplest kind of loop in PHP. They&#8217;re pretty much just saying &#8220;Do something for a while until a certain condition is satisfied&#8221;. You could be saying Stay at work until this project is finished or Keep on running this marathon until you get to the end</p>
<p>The general syntax of a while loop is as follows</p>

<div class="wp_syntax"><div class="code"><pre class="text">while(condition = true) {
  do something
}</pre></div></div>

<p>A real-world code example of this might be</p>
<pre class="php">$miles_completed = 0;
$race_finished = false;
while&#40;$race_finished == false&#41; &#123;
  $miles_completed++;
  if&#40;$miles_completed &gt;= 26&#41;&#123;
    $race_finished = true;
  &#125;
&#125;</pre>
<p>I&#8217;ll explain some of the symbols and operations going on here&#8230;</p>
<p>Lines 1 and 2 : we initialise the values of $miles_completed and $race_finished. The code wouldn&#8217;t work properly otherwise, as $race_completed has to be equal to FALSE initially to satisfy the while loop in line 3<br />
Line 3 : The while loop will repeat as long as $race_finished is equal to false. A drawback of while loops is that they can loop indefinitely if you are not careful, and this will cause your application to crash - you can see how this would occur if we didn&#8217;t increment the value of $miles_completed or set $race_completed to be true. You&#8217;d be running that marathon for ever!<br />
Line 4 : the expression $miles_completed++; is a way of saying $miles_completed = $miles_completed+1; This can also be rewritten as $miles_completed += 1;<br />
Line 5 : we check the value of $miles_completed on every repetition of the loop. Once $miles_completed becomes greater than 10 (since we are incrementing the value every time round) then $rage_finished is set to TRUE, therefore breaking the condition that keeps the loop going</p>
<p>Another way of writing while loops is to invoke the &#8220;do&#8221; statement</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$miles_completed</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$race_finished</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">false</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">do</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000033;">$miles_completed</span><span style="color: #339933;">++;</span>
  <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$miles_completed</span> <span style="color: #339933;">&gt;=</span> <span style="color: #cc66cc;">26</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #000033;">$race_finished</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">true</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$race_finished</span> <span style="color: #339933;">==</span> <span style="color: #000000; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The only difference here is that the statement between do.. and ..while will always be executed at least once before the loop begins. So, for example, the code</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$line</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;Texty texty text text&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$a</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">do</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #990000;">echo</span> <span style="color: #000033;">$line</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$a</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>will output</p>

<div class="wp_syntax"><div class="code"><pre class="php">Texty texty text text</pre></div></div>

<p>even though the condition of the while loop (that a must equal 2) is false</p>
<p><a name='For loops'></a><br />
<h3>For loops</h3>
<p>For loops are probably the most common type of loop found in PHP, and indeed in most other kinds of programming language. They can be used to loop through a series of repetitions like a while loop, but with some advantages. It&#8217;s not so easy to create a for loop that will never end, since the code to define the &#8220;exit condition&#8221; as well as the code to increment the count for the loop are defined explicitly at the start</p>
<p>The syntax of for-loops is as follows</p>

<div class="wp_syntax"><div class="code"><pre class="text">for(loop initialisation code; the loop &quot;exit condition&quot;; code to evaluate before each loop){
  //the code to execute on each loop goes in here
}</pre></div></div>

<p>A more concrete example of the for loop, and the most commonly encountered style is</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$i</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> <span style="color: #000033;">$i</span></pre></div></div>

<p>$i = 0 : This sets up the variable $i for the purpose of the loop. In this instance, we&#8217;re going to continually check the value of $i after every loop, and only exit when the second element evaluates to true&#8230;<br />
$i < 100 : Since we initially set $i = 0, then this statement will initially evaluate to false. The loop will exit only after this condition becomes true, which is the task of the final element&#8230;<br />
$i++ : This statement says that we want to increment the value of $i after every loop. After 100 loops, $i will be greater than 100, so the loop will exit successfully</p>
<p>This for loop will produce the output</p>

<div class="wp_syntax"><div class="code"><pre class="text">i = 0
i = 1
i = 2
(... and so on)</pre></div></div>

<p>Some other examples of for loops, using slightly different code</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$i</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">50</span><span style="color: #339933;">;</span> <span style="color: #000033;">$i</span><span style="color: #339933;">&gt;</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> <span style="color: #000033;">$i</span><span style="color: #339933;">--</span><span style="color: #009900;">&#41;</span> <span style="color: #666666; font-style: italic;">/* same as before, but decreasing $i */</span>
<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$i</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> <span style="color: #000033;">$i</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> <span style="color: #000033;">$i</span><span style="color: #339933;">=</span><span style="color: #990000;">substr</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$i</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span> <span style="color: #339933;">,</span><span style="color: #990000;">strlen</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$i</span><span style="color: #009900;">&#41;</span><span style="color: #cc66cc;">-1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #990000;">echo</span> <span style="color: #000033;">$i</span><span style="color: #339933;">;</span>   
<span style="color: #009900;">&#125;</span>
<span style="color: #666666; font-style: italic;">// this prints out...</span>
<span style="color: #666666; font-style: italic;">// Hello</span>
<span style="color: #666666; font-style: italic;">// Hell</span>
<span style="color: #666666; font-style: italic;">// Hel</span>
<span style="color: #666666; font-style: italic;">// He</span>
<span style="color: #666666; font-style: italic;">// H</span></pre></div></div>

<p><a name='Foreach loops'></a><br />
<h3>Foreach loops</h3>
<p>Foreach loops are a particularly useful feature of PHP when working with arrays as they allow us to iterate through all the values of an array in sequence. Foreach loops also allow us to access the keys of an array, which is a useful feature when working with associative arrays.</p>
<p>An example of the foreach syntax is</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #666666; font-style: italic;">/* three people, and their respective scores in a test*/</span>
<span style="color: #000033;">$scores</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;jeff&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #cc66cc;">74</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;bill&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #cc66cc;">88</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;john&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #cc66cc;">63</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$scores</span> <span style="color: #b1b100;">as</span> <span style="color: #000033;">$value</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #990000;">echo</span> <span style="color: #000033;">$value</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The &#8220;as&#8221; keyword is used to assign each value in the array to a temporary variable for use within the loop. Inside the loop, operations can be carried out on each value in turn. The above code will output</p>

<div class="wp_syntax"><div class="code"><pre class="text">74
88
63</pre></div></div>

<p>If we wish to perform operations on keys as well as values, we can make a slight adjustment to the syntax</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$scores</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;jeff&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #cc66cc;">74</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;bill&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #cc66cc;">88</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;john&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #cc66cc;">63</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$scores</span> <span style="color: #b1b100;">as</span> <span style="color: #000033;">$key</span> <span style="color: #339933;">=&gt;</span> <span style="color: #000033;">$value</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;$key, $value&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The operator => is used to let PHP know that we want to assign a temporary variable to each key in the array as well as each value. In the case of an indexed array, where we haven&#8217;t explicitly defined the keys, each key will simply be an incremental numerical value - 0, 1, 2 etc.</p>

<div class="wp_syntax"><div class="code"><pre class="text">jeff, 74
bill, 88
john, 63</pre></div></div>

<p>When performing operations on an array, it&#8217;s often useful to be able to modify the contents of the array in some way. Here, we might want to replace each score with a &#8220;pass&#8221; or &#8220;fail&#8221; depending on whether the score is above the pass mark (let&#8217;s say 70 in this case)</p>
<p>We can make use of the &#8220;pass by reference&#8221; functionality of PHP to state that the temporary variable $value shouldn&#8217;t be assigned the actual value of each array element, but instead should point directly to that array element, like so</p>
<pre class="php">$scores = array&#40;&quot;jeff&quot; =&gt; 74, &quot;bill&quot; =&gt; 88, &quot;john&quot; =&gt; 63&#41;;
foreach&#40;$scores as &amp;$value&#41;&#123;
  if&#40;$value &gt;= 70&#41;
    $value = &quot;pass&quot;;
  else
    $value = &quot;fail&quot;;
&#125;
unset&#40;$value&#41;;
print_r&#40;$scores&#41;;</pre>
<p>This will give us</p>

<div class="wp_syntax"><div class="code"><pre class="text">Array (
  [jeff] =&gt; pass
  [bill] =&gt; pass
  [john] =&gt; fail
)</pre></div></div>

<p>Notice in line 8 of the above code, we use the statement unset($value). This is because, after iterating through an array passed by reference in this way, references to the final element of the array, and to $value still remain, so it&#8217;s good practice to destroy them via the use of the unset() function.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.roughguidetophp.com/loops-in-php-while-and-for/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Pagination : Splitting data across multiple pages with MySQL and PHP</title>
		<link>http://www.roughguidetophp.com/pagination-splitting-data-across-multiple-pages-with-mysql-and-php/</link>
		<comments>http://www.roughguidetophp.com/pagination-splitting-data-across-multiple-pages-with-mysql-and-php/#comments</comments>
		<pubDate>Tue, 30 Nov 1999 00:00:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Advanced PHP]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[
 
(The files used in this tutorial are available to download here)

Pagination
Sometimes when working with a MySQL powered website in PHP, we’ll come across situations where we have multiple records that we wish to display to the visitor. If there are many tens, hundreds or more of these results, we might not want them all shown [...]]]></description>
			<content:encoded><![CDATA[<p><!--pagetitle:Using LIMIT and the query string to retrieve particular results--></p>
<p> </p>
<p>(The files used in this tutorial are available to <a href="http://www.roughguidetophp.com/wp-content/uploads/2008/09/name_meanings.zip">download here</a>)</p>
<p><a name="Pagination"></a></p>
<h3>Pagination</h3>
<p>Sometimes when working with a MySQL powered website in PHP, we’ll come across situations where we have multiple records that we wish to display to the visitor. If there are many tens, hundreds or more of these results, we might not want them all shown on the one page as this would increase the loading time, and make the list harder to navigate.</p>
<p>To solve this problem, we introduce the concept of pagination in MySQL, which makes use of the handy LIMIT keyword and information passed by GET from the URL query string</p>
<p><a name="Using LIMIT to specify a range of records in MySQL"></a></p>
<h3>Using LIMIT to specify a range of records in MySQL</h3>
<p>For this example, we’re going to use a table of records containing popular boys and girls names beginning with “S” along with their general meaning. Because this table contains a lot of entries, I’m not going to display it all here, but the accompanying SQL file contains all the information you need to import the table into your MySQL database. Once you’ve done that, you can then proceed with the tutorial to learn how to split this data into pages and display the pages to your visitors along with a handy navigation bar.</p>
<p><a href="http://www.roughguidetophp.com/wp-content/uploads/2008/09/name_meanings.sql">download the full table in SQL here</a></p>
<table border="0">
<tbody>
<tr>
<td>Name</td>
<td>Meaning</td>
</tr>
<tr>
<td>Ragnvald</td>
<td>Means “friend of God” in Hebrew</td>
</tr>
<tr>
<td>Raguel</td>
<td>Means “spacious” in Hebrew</td>
</tr>
<tr>
<td>Rahab</td>
<td>From the Old Norse name Ragnvaldr, a cognate of Reginwald</td>
</tr>
<tr>
<td>…</td>
<td>…231 more…</td>
</tr>
</tbody>
</table>
<p>Let’s perform our first query on this data to retrieve the first 30 records in the list. This is the main query we will be using to build our pagination application shortly</p>

<div class="wp_syntax"><div class="code"><pre class="sql"><span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #66cc66;">*</span> <span style="color: #993333; font-weight: bold;">FROM</span> name_meanings <span style="color: #993333; font-weight: bold;">LIMIT</span> <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">,</span> <span style="color: #cc66cc;">30</span> <span style="color: #993333; font-weight: bold;">ORDER</span> <span style="color: #993333; font-weight: bold;">BY</span> id <span style="color: #993333; font-weight: bold;">ASC</span></pre></div></div>

<p>If you run this SQL query, you’ll see the results returned are limited to only 30 and, more importantly, only the first 30. The LIMIT keyword takes, as arguments, two values - first, the record to start counting from and second, the number of records to return. So here, we could from record 0 and return 30 records. To return our second “page” of results, we would use</p>

<div class="wp_syntax"><div class="code"><pre class="sql"><span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #66cc66;">*</span> <span style="color: #993333; font-weight: bold;">FROM</span> name_meanings <span style="color: #993333; font-weight: bold;">LIMIT</span> <span style="color: #cc66cc;">30</span><span style="color: #66cc66;">,</span> <span style="color: #cc66cc;">30</span> <span style="color: #993333; font-weight: bold;">ORDER</span> <span style="color: #993333; font-weight: bold;">BY</span> id <span style="color: #993333; font-weight: bold;">ASC</span></pre></div></div>

<p>Which then returns another 30 records, but this time returns the rows starting from record 30.  We’re also using the ORDER BY keyword here, just to ensure that the results are ordered correctly. At the end of the tutorial, we’ll see how we can use the ORDER BY feature to add even more functionality to our site!</p>
<p>This is the fundamental principle behind creating a pagination system. We’ll now look to see how we can specify which page we want to view, and give the visitor control over this variable.</p>
<p><a name="Passing the Current Page Number via the Query String"></a></p>
<h3>Passing the Current Page Number via the Query String</h3>
<p>to actually determine which page to show at any given time, we’re going to build a little PHP script. This script will do a couple of things. Firstly, it’ll display whatever records we’re interested in, in a nicely formatted table and secondly, it will retrieve the current page we wish to view via the $_GET variable. (The $_GET array always contains any variables passed in the query string, e.g. if the URL is index.php?my_var=123, then the value of $_GET['my_var'] will be 123)</p>
<p>Let’s take a look at this code. This file is also available in the tutorial zip archive <a href="http://www.roughguidetophp.com/wp-content/uploads/2008/09/name_meanings.sql">downloadable from here</a></p>

<div class="wp_syntax"><div class="code"><pre class="php">&nbsp;
Name Meanings
&nbsp;
<span style="color: #339933;">&lt;</span>html<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>html<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>head<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>title<span style="color: #339933;">&gt;</span>Name Meanings<span style="color: #339933;">&lt;/</span>title<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>style<span style="color: #339933;">&gt;</span>
html <span style="color: #009900;">&#123;</span>font<span style="color: #339933;">-</span>family<span style="color: #339933;">:</span>tahoma<span style="color: #339933;">,</span>verdana<span style="color: #339933;">,</span>arial<span style="color: #339933;">,</span>sans serif<span style="color: #339933;">;</span><span style="color: #009900;">&#125;</span>
body <span style="color: #009900;">&#123;</span>font<span style="color: #339933;">-</span>size<span style="color: #339933;">:</span><span style="color: #cc66cc;">62.5</span><span style="color: #339933;">%;</span><span style="color: #009900;">&#125;</span>
table tr th<span style="color: #009900;">&#123;</span>
    font<span style="color: #339933;">-</span>size<span style="color: #339933;">:</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">.</span>8em<span style="color: #339933;">;</span>
    background<span style="color: #339933;">-</span>color<span style="color: #339933;">:</span><span style="color: #666666; font-style: italic;">#ddb;    </span>
    padding<span style="color: #339933;">:</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">.</span>2em <span style="color: #cc66cc;">0</span><span style="color: #339933;">.</span>6em <span style="color: #cc66cc;">0</span><span style="color: #339933;">.</span>2em <span style="color: #cc66cc;">0</span><span style="color: #339933;">.</span>6em<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
table tr td<span style="color: #009900;">&#123;</span>
    font<span style="color: #339933;">-</span>size<span style="color: #339933;">:</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">.</span>8em<span style="color: #339933;">;</span>
    background<span style="color: #339933;">-</span>color<span style="color: #339933;">:</span><span style="color: #666666; font-style: italic;">#eec;</span>
    margin<span style="color: #339933;">:</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">.</span>3em<span style="color: #339933;">;</span>
    padding<span style="color: #339933;">:</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">.</span>3em<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #339933;">&lt;/</span>style<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;/</span>head<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>body<span style="color: #339933;">&gt;</span>
<span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #666666; font-style: italic;">//we always start out by connecting to our database</span>
<span style="color: #666666; font-style: italic;">//using a handy external file, db_connect.php</span>
<span style="color: #b1b100;">include</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;db_connect.php&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">//fetch our page number from the query string</span>
<span style="color: #666666; font-style: italic;">//the URL should look something like</span>
<span style="color: #666666; font-style: italic;">//name_meanings.php?page=4</span>
<span style="color: #000033;">$page</span> <span style="color: #339933;">=</span> <span style="color: #000033;">$_GET</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'page'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">//define how many records we want to show per page</span>
<span style="color: #000033;">$records_per_page</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">15</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>filter_var<span style="color: #009900;">&#40;</span><span style="color: #000033;">$page</span><span style="color: #339933;">,</span> VALIDATE_INT<span style="color: #339933;">,</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #000033;">$page</span><span style="color: #339933;">=</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>   
<span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;&lt;h3&gt;Showing results for page $page&lt;/h3&gt;&quot;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">//calculate the offset value to start counting from</span>
<span style="color: #666666; font-style: italic;">//in the MySQL query. To do this, we multiply the page</span>
<span style="color: #666666; font-style: italic;">//number, minus one, by the number of records we want</span>
<span style="color: #666666; font-style: italic;">//to show per page</span>
<span style="color: #666666; font-style: italic;">//e.g. for page 1 - Our starting record will be (1-1)*30</span>
<span style="color: #000033;">$offset</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #000033;">$page</span><span style="color: #cc66cc;">-1</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> <span style="color: #000033;">$records_per_page</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$result</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;SELECT * FROM name_meanings ORDER BY id ASC LIMIT $offset, $records_per_page&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;&lt;table&gt;&lt;tr&gt;&lt;th&gt;Name&lt;/th&gt;&lt;th&gt;Name Meaning&lt;/th&gt;&lt;/tr&gt;&quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$row</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_fetch_array</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$result</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">do</span><span style="color: #009900;">&#123;</span>
    <span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;&lt;tr&gt;&lt;td&gt;{$row[&quot;</span>name<span style="color: #0000ff;">&quot;]}&lt;/td&gt;&lt;td&gt;{$row[&quot;</span>meaning<span style="color: #0000ff;">&quot;]}&lt;/td&gt;&lt;/tr&gt;&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$row</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_fetch_array</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$result</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  
<span style="color: #009900;">&#125;</span>
<span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;&lt;/table&gt;&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span>
<span style="color: #339933;">&lt;/</span>body<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;/</span>html<span style="color: #339933;">&gt;</span></pre></div></div>

<p>This code will display on screen, a simple list of names and, depending on the query string appended to the URL, will start from a different point in the list, like so</p>
<p><a href="http://www.roughguidetophp.com/wp-content/uploads/2008/09/results.jpg"><img class="size-full wp-image-433" title="results" src="http://www.roughguidetophp.com/wp-content/uploads/2008/09/results.jpg" alt="Different query strings produce different tables" width="442" height="567" /></a></p>
<p class="wp-caption-text">Different query strings produce different tables</p>
<p>You can see how the URL name_meanings.php produces a different table to name_meanings.php?page=3</p>
<p><a name="Constructing the Page Navigation Links using PHP"></a></p>
<h3>Constructing the Page Navigation Links using PHP</h3>
<p>Now that we’ve created a system to allow us to display any page of results, we need to hand control to this over to the user. To do this, we can create a series of hyperlinks, all pointing back to the current page, but with a different value appended to the URL. The following code, appended to the end of the previous code, before the &lt;/body&gt; and &lt;/html&gt; tags,  will achieve this</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;&lt;p&gt;Navigation&lt;/p&gt;&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$count_result</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;SELECT COUNT(*) FROM name_meanings&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$count_row</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_fetch_array</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$count_result</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">//fetch the total number of rows in the table</span>
<span style="color: #000033;">$count</span> <span style="color: #339933;">=</span> <span style="color: #000033;">$count_row</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;COUNT(*)&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">//we will use this information to build our navigation list</span>
<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$i</span><span style="color: #339933;">=</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span> <span style="color: #000033;">$i</span><span style="color: #339933;">&lt;=</span><span style="color: #000033;">$count</span><span style="color: #339933;">/</span><span style="color: #000033;">$records_per_page</span><span style="color: #339933;">;</span> <span style="color: #000033;">$i</span><span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;&lt;a href='name_meanings.php?page=$i'&gt;$i&lt;/a&gt;&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #666666; font-style: italic;">//output a little symbol (|) to seperate the links</span>
  <span style="color: #666666; font-style: italic;">//but not for the last link</span>
  <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$i</span><span style="color: #339933;">!=</span><span style="color: #000033;">$records_per_page</span><span style="color: #009900;">&#41;</span>
    <span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot; | &quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Reload your name_meanings.php file, and you should see a list of 16 links underneath the table, you can click on any of these to go to any of the pages.</p>
<p>How about if we add next and previous links to make navigation even easier? And also make the current page link inactive, so we can’t click on the same page link that we’re already viewing No problem! Make the following adjustment to the above code</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;&lt;p&gt;Navigation&lt;/p&gt;&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$count_result</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;SELECT COUNT(*) FROM name_meanings&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$count_row</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_fetch_array</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$count_result</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">//fetch the total number of rows in the table</span>
<span style="color: #000033;">$count</span> <span style="color: #339933;">=</span> <span style="color: #000033;">$count_row</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;COUNT(*)&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">//we will use this information to build our navigation list</span>
<span style="color: #990000;">echo</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$page</span><span style="color: #339933;">&gt;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span>?<span style="color: #0000ff;">&quot;&lt;a href='name_meanings.php?page=&quot;</span><span style="color: #339933;">.</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$page</span><span style="color: #cc66cc;">-1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;'&gt;prev&lt;/a&gt;&quot;</span><span style="color: #339933;">:</span><span style="color: #0000ff;">&quot;prev&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot; | &quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$i</span><span style="color: #339933;">=</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span> <span style="color: #000033;">$i</span><span style="color: #339933;">&lt;=</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$count</span><span style="color: #339933;">/</span><span style="color: #000033;">$records_per_page</span><span style="color: #009900;">&#41;</span><span style="color: #cc66cc;">+1</span><span style="color: #339933;">;</span> <span style="color: #000033;">$i</span><span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$i</span><span style="color: #339933;">!=</span><span style="color: #000033;">$page</span><span style="color: #009900;">&#41;</span>
    <span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;&lt;a href='name_meanings.php?page=$i'&gt;$i&lt;/a&gt;&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">else</span>
    <span style="color: #990000;">echo</span> <span style="color: #000033;">$i</span><span style="color: #339933;">;</span>
  <span style="color: #666666; font-style: italic;">//output a little symbol (|) to seperate the links</span>
  <span style="color: #666666; font-style: italic;">//but not for the last link</span>
  <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$i</span><span style="color: #339933;">&lt;</span><span style="color: #000033;">$count</span><span style="color: #339933;">/</span><span style="color: #000033;">$records_per_page</span><span style="color: #009900;">&#41;</span>
    <span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot; | &quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot; | &quot;</span><span style="color: #339933;">.</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$page</span><span style="color: #339933;">&lt;</span><span style="color: #000033;">$count</span><span style="color: #339933;">/</span><span style="color: #000033;">$records_per_page</span><span style="color: #009900;">&#41;</span>?<span style="color: #0000ff;">&quot;&lt;a href='name_meanings.php?page=&quot;</span><span style="color: #339933;">.</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$page</span><span style="color: #cc66cc;">+1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;'&gt;next&lt;/a&gt;&quot;</span><span style="color: #339933;">:</span><span style="color: #0000ff;">&quot;next&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Resulting in…</p>
<p><img class="size-full wp-image-434" title="navi" src="http://www.roughguidetophp.com/wp-content/uploads/2008/09/navi.jpg" alt="Behold! The power of navigation!" width="447" height="470" /></p>
<p class="wp-caption-text">Behold! The power of navigation!</p>
<p>See how we’ve made it so that the next and prev links are inactive if we’re on the last and first pages respectively? We can do this by performing some checks on the current values of $page and $count/$records_per_page (which gives us the maximum page number)</p>
<p>Note here that $count/$records_per_page actually gives us a value of 16.6, which we can still work with, but for a more accurate count of the full number of pages, you’d use floor($count/$records_per_page) to get 16</p>
<p><a name="Keeping track of the Query String variables and Adding New Ones"></a></p>
<h3>Keeping track of the Query String variables and Adding New Ones</h3>
<p>What if you already have an application you want to add pagination to, which makes use of query strings? Consider the following example and imagine that the query string variable section=code is actually important, and we mustn’t lose it when changing page</p>

<div class="wp_syntax"><div class="code"><pre class="text">name_meanings.php?section=code&amp;amp;page=5</pre></div></div>

<p>If we just stuck with the code above, our navigation links would direct us to the following pages</p>

<div class="wp_syntax"><div class="code"><pre class="text">name_meanings.php?page=1
name_meanings.php?page=2
...etc</pre></div></div>

<p>Which is not good! We’ve lost our original query string variable, and so whatever purpose it served has now been lost and the page may display wrongly.  However, using some simple PHP code, we can create a function that will automatically generate a valid link for us, complete with whatever variable we choose to append to it. The function is as follows (we’ll name it build_url() )</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">function</span> build_url<span style="color: #009900;">&#40;</span><span style="color: #000033;">$filename</span><span style="color: #339933;">,</span> <span style="color: #000033;">$key</span><span style="color: #339933;">,</span> <span style="color: #000033;">$value</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #000033;">$values</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000033;">$query_str</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #666666; font-style: italic;">//get the query string arguments and store them in</span>
  <span style="color: #666666; font-style: italic;">//the $values array</span>
  <span style="color: #990000;">parse_str</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$_SERVER</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'QUERY_STRING'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #000033;">$values</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #666666; font-style: italic;">//loop through the $values array and add the appropriate </span>
  <span style="color: #666666; font-style: italic;">//keys to the query string</span>
  <span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$values</span> <span style="color: #b1b100;">as</span> <span style="color: #000033;">$k</span><span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span><span style="color: #000033;">$v</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">//IF, though, a key in the existing query string matches the same key</span>
    <span style="color: #666666; font-style: italic;">//we're trying to add, ignore it, since we'll add it manually in a moment</span>
    <span style="color: #666666; font-style: italic;">//This prevents having multiples of the same keys</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$k</span><span style="color: #339933;">!=</span><span style="color: #000033;">$key</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
      <span style="color: #000033;">$query_str</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;{$k}={$v}&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#125;</span>
  <span style="color: #666666; font-style: italic;">//add in our new key and value</span>
  <span style="color: #000033;">$query_str</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;{$key}={$value}&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #666666; font-style: italic;">//reconstruct the full URL using the implode() function to piece together all</span>
  <span style="color: #666666; font-style: italic;">//the query string values in the $query_string array, joining them together with &quot;&amp;amp;&quot;  </span>
  <span style="color: #b1b100;">return</span> <span style="color: #0000ff;">&quot;$filename?&quot;</span><span style="color: #339933;">.</span><span style="color: #990000;">implode</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;&amp;amp;&quot;</span><span style="color: #339933;">,</span> <span style="color: #000033;">$query_str</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>And we’ll rewrite some of our code to use this function to generate our links</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #990000;">echo</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$page</span><span style="color: #339933;">&gt;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span>?<span style="color: #0000ff;">&quot;&lt;a href='&quot;</span><span style="color: #339933;">.</span>build_url<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;name_meanings.php&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;page&quot;</span><span style="color: #339933;">,</span> <span style="color: #000033;">$page</span><span style="color: #cc66cc;">-1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;'&gt;prev&lt;/a&gt;&quot;</span><span style="color: #339933;">:</span><span style="color: #0000ff;">&quot;prev&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot; | &quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$i</span><span style="color: #339933;">=</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span> <span style="color: #000033;">$i</span><span style="color: #339933;">&lt;=</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$count</span><span style="color: #339933;">/</span><span style="color: #000033;">$records_per_page</span><span style="color: #009900;">&#41;</span><span style="color: #cc66cc;">+1</span><span style="color: #339933;">;</span> <span style="color: #000033;">$i</span><span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$i</span><span style="color: #339933;">!=</span><span style="color: #000033;">$page</span><span style="color: #009900;">&#41;</span>
    <span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;&lt;a href='&quot;</span><span style="color: #339933;">.</span>build_url<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;name_meanings.php&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;page&quot;</span><span style="color: #339933;">,</span> <span style="color: #000033;">$i</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;'&gt;$i&lt;/a&gt;&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">else</span>
    <span style="color: #990000;">echo</span> <span style="color: #000033;">$i</span><span style="color: #339933;">;</span>
  <span style="color: #666666; font-style: italic;">//output a little symbol (|) to seperate the links</span>
  <span style="color: #666666; font-style: italic;">//but not for the last link</span>
  <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$i</span><span style="color: #339933;">&lt;</span><span style="color: #000033;">$count</span><span style="color: #339933;">/</span><span style="color: #000033;">$records_per_page</span><span style="color: #009900;">&#41;</span>
    <span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot; | &quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot; | &quot;</span><span style="color: #339933;">.</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$page</span><span style="color: #339933;">&lt;</span><span style="color: #000033;">$count</span><span style="color: #339933;">/</span><span style="color: #000033;">$records_per_page</span><span style="color: #009900;">&#41;</span>?<span style="color: #0000ff;">&quot;&lt;a href='&quot;</span><span style="color: #339933;">.</span>build_url<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;name_meanings.php&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;page&quot;</span><span style="color: #339933;">,</span> <span style="color: #000033;">$page</span><span style="color: #cc66cc;">+1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;'&gt;next&lt;/a&gt;&quot;</span><span style="color: #339933;">:</span><span style="color: #0000ff;">&quot;next&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Using this function, we can now enter a URL like</p>

<div class="wp_syntax"><div class="code"><pre class="text">name_meanings.php?section=code&amp;amp;page=5</pre></div></div>

<p>and our page links will still be valid.</p>
<p><a name="Creating a “Sort By” option with ORDER"></a></p>
<h3>Creating a “Sort By” option with ORDER</h3>
<p>Now that we’ve introduced a function to keep our URLs intact, this opens up an interesting new possibility, we can now add more than one search parameter to our table, to allow us to further refine our results. Let’s add a couple of options, first a direction option to choose whether we want the table in ascending or descending order, and another option sort by to state whether we want to sort by “name” or by “meaning”. Add the following code, near the end of the file…</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;Table Order&quot;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;direction : &quot;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">echo</span> <span style="color: #000033;">$dir</span><span style="color: #339933;">==</span><span style="color: #0000ff;">&quot;ASC&quot;</span>?<span style="color: #0000ff;">&quot;Ascending&quot;</span><span style="color: #339933;">:</span><span style="color: #0000ff;">&quot;Ascending&quot;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot; | &quot;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">echo</span> <span style="color: #000033;">$dir</span><span style="color: #339933;">==</span><span style="color: #0000ff;">&quot;DESC&quot;</span>?<span style="color: #0000ff;">&quot;Descending&quot;</span><span style="color: #339933;">:</span><span style="color: #0000ff;">&quot;Descending&quot;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;sort by : &quot;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">echo</span> <span style="color: #000033;">$sort</span><span style="color: #339933;">==</span><span style="color: #0000ff;">&quot;name&quot;</span>?<span style="color: #0000ff;">&quot;Name&quot;</span><span style="color: #339933;">:</span><span style="color: #0000ff;">&quot;Name&quot;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot; | &quot;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">echo</span> <span style="color: #000033;">$sort</span><span style="color: #339933;">==</span><span style="color: #0000ff;">&quot;meaning&quot;</span>?<span style="color: #0000ff;">&quot;Meaning&quot;</span><span style="color: #339933;">:</span><span style="color: #0000ff;">&quot;Meaning&quot;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This will create the appropriate links to jump to the necessary page URL. We’re looking to have URLs along the lines of</p>

<div class="wp_syntax"><div class="code"><pre class="text">name_meanings.php?page=5&amp;amp;sort=name&amp;amp;dir=asc</pre></div></div>

<p>We also need to add code earlier in the file to deal with these new variables. Near the top of the file, before the main SQL query</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #666666; font-style: italic;">//get the direction we'd like to sort our results in. Defaults to ASC</span>
<span style="color: #000033;">$dir</span> <span style="color: #339933;">=</span> <span style="color: #990000;">strtoupper</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$_GET</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'dir'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$dir</span><span style="color: #339933;">!=</span><span style="color: #0000ff;">&quot;ASC&quot;</span> <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;&amp;</span>amp<span style="color: #339933;">;</span> <span style="color: #000033;">$dir</span><span style="color: #339933;">!=</span><span style="color: #0000ff;">&quot;DESC&quot;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #000033;">$dir</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;ASC&quot;</span><span style="color: #339933;">;</span>
 
<span style="color: #666666; font-style: italic;">//get the database value to sort by. Defaults to &quot;name&quot;</span>
<span style="color: #000033;">$sort</span> <span style="color: #339933;">=</span> <span style="color: #000033;">$_GET</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'sort'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$sort</span><span style="color: #339933;">!=</span><span style="color: #0000ff;">&quot;name&quot;</span> <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;&amp;</span>amp<span style="color: #339933;">;</span> <span style="color: #000033;">$sort</span><span style="color: #339933;">!=</span><span style="color: #0000ff;">&quot;meaning&quot;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #000033;">$sort</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;name&quot;</span><span style="color: #339933;">;</span></pre></div></div>

<p>And make the following changes to the SQL query itself</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$result</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;SELECT * FROM name_meanings ORDER BY $sort $dir LIMIT $offset, $records_per_page&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>You should now be able to load up the page, and see your new navigation links working fully! Try changing the sort order of the table - note that, when sorting by “meaning”, the blank entries will show up first.</p>
<p><img class="size-full wp-image-435" title="ordering" src="http://www.roughguidetophp.com/wp-content/uploads/2008/09/ordering.jpg" alt="Now we have even more control!" width="451" height="539" /></p>
<p class="wp-caption-text">Now we have even more control!</p>
<p><a name="Conclusion"></a></p>
<h3>Conclusion</h3>
<p>You should now have a simple knowledge of the basics of pagination for PHP and MySQL. As you’ve progressed through this tutorial, you may have noticed some shortfalls in the script, and areas for improvement. One of the things I haven’t mentioned, but which you may well want to try and implement yourself, is a way to get round the problem that the pagelinks themselves could get pretty numerous!. Try and find some interesting way of displaying the links so that you perhaps see them like this</p>

<div class="wp_syntax"><div class="code"><pre class="text">prev | 1 | 2 ... 8 | 9 | 10 .... 20 | 21 | next</pre></div></div>

<p>If you get really stuck, email me and I might let you know the solution <img class="wp-smiley" src="http://www.roughguidetophp.com/wp-includes/images/smilies/icon_smile.gif" alt=":)" /></p>
<p>The files used in this tutorial are available to <a href="http://www.roughguidetophp.com/wp-content/uploads/2008/09/name_meanings.zip">download here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.roughguidetophp.com/pagination-splitting-data-across-multiple-pages-with-mysql-and-php/feed/</wfw:commentRss>
		</item>
		<item>
		<title>PHP Image manipulation with GD2</title>
		<link>http://www.roughguidetophp.com/php-image-manipulation-with-gd2/</link>
		<comments>http://www.roughguidetophp.com/php-image-manipulation-with-gd2/#comments</comments>
		<pubDate>Tue, 30 Nov 1999 00:00:00 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[Advanced PHP]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[
One of the more surprising things you can learn about PHP is that it&#8217;s actually very useful when it comes to manipulating images of varying filetypes and formats. And a good thing too, since a lot of the internet is made up of pictures!
The functionality of PHP in terms of image manipulation ranges from very [...]]]></description>
			<content:encoded><![CDATA[<p><!--pagetitle:PHP and images, an introduction--><br />
One of the more surprising things you can learn about PHP is that it&#8217;s actually very useful when it comes to manipulating images of varying filetypes and formats. And a good thing too, since a lot of the internet is made up of pictures!</p>
<p>The functionality of PHP in terms of image manipulation ranges from very simple resizing of images through to more complex effects and functions using image libraries such as ImageMagick</p>
<p>In this tutorial, I&#8217;ll take you through some of the more common uses for PHP when manipulating images, and then introduce you to some of the cooler aspects of this powerful little tool, which could help you to really add a bit of jazz and sparkle to your website!</p>
<p>Let&#8217;s start with something simple. We&#8217;ll take a particular image, how about, let&#8217;s say, an <a href="http://www.roughguidetophp.com/wp-content/uploads/2008/08/puppy.jpg">image of a cute puppy</a> and then run some functions on it to determine a few facts about it.</p>
<p><a name='getimagesize()'></a><br />
<h3>getimagesize()</h3>
<p>We&#8217;ll start here by determining the image type (is it a jpeg, gif, png?), dimensions (height and width) and a few other things by using the getimagesize() function.  Note that for this example, the image we&#8217;re using - puppy.jpg - must be in the same directory as the PHP script we&#8217;re calling this function from</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$info</span> <span style="color: #339933;">=</span> <span style="color: #990000;">getimagesize</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;puppy.jpg&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">print_r</span> <span style="color: #009900;">&#40;</span><span style="color: #000033;">$info</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The function returns an array containing all of the relevant information, so the above code will produce</p>

<div class="wp_syntax"><div class="code"><pre class="text">Array (
  [0] =&gt; 491 //width
  [1] =&gt; 367 //height
  [2] =&gt; 2 //this number is a constant representing the image type
  [3] =&gt; width=&quot;491&quot; height=&quot;367&quot;
  [bits] =&gt; 8  //number of bits-per-pixel in the image
  [channels] =&gt; 3 // 3 = RGB, 4 = CMYK
  [mime] =&gt; image/jpeg //determines the filetype
)</pre></div></div>

<p>From this we can tell the image is 491 by 367 pixels in size, with an 8-bit colour depth, and 3 colour channels. We also have the filetype, stored as the &#8220;mime&#8221; value of the array - &#8220;image/jpeg&#8221;.</p>
<p>Another way we can retrieve the type of image used is to make use of PHP&#8217;s image_type_to_extension() function which will take, as its argument, the value of the array in index &#8220;2&#8243; - in this case a value of 2, which represents the filetype of the image. So, for this value we get</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #990000;">echo</span> image_type_to_extension<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>which outputs</p>

<div class="wp_syntax"><div class="code"><pre class="text">.jpeg</pre></div></div>

<p>So, now we have this information, what else can we do with the file? We could try resizing the image, and saving a new copy of it. But first, let&#8217;s just try reading in the file data and see what happens</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #990000;">header</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Content-Type: image/jpeg&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$image</span> <span style="color: #339933;">=</span> <span style="color: #339933;">@</span>imagecreatefromjpeg<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;puppy.jpg&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
imagejpeg<span style="color: #009900;">&#40;</span><span style="color: #000033;">$image</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
imagedestroy<span style="color: #009900;">&#40;</span><span style="color: #000033;">$image</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p><a href="http://www.roughguidetophp.com/wp-content/uploads/2008/08/puppy.jpg"><img class="size-medium wp-image-244" title="puppy" src="http://www.roughguidetophp.com/wp-content/uploads/2008/08/puppy-300x224.jpg" alt="And behold, a picture of a cute puppy!" width="300" height="224" /></a>
<p class="wp-caption-text">And behold, a picture of a cute puppy!</p>
<p>Line 1  : This header value tells the browser to interpret the following data as Jpeg image data<br />
Line 2  : Read the image data from the file, puppy.jpg using imagecreatefromjpeg(). The @ symbol simply supresses any errors that might occur. This creates a GD Resource $image, which can then be manipulated as required, or sent as output to the browser. Function like this one are part of PHP&#8217;s GD2 Library of image manipulation functions. Each function works on, or loads/saves an object representing image data called a GD Resource.<br />
Line 3  : imagejpeg() is the function that outputs the image data to the browser<br />
Line 4  : After we have output the image data, destroy the image resource with imagedestroy()</p>
<p>So that&#8217;s how we read in and print out simple jpeg data. Similar functions also exist for PNG and GIF filetypes - namely imagecreatefromgif(), imagegif() and imagecreatefrompng(), imagepng()</p>
<p><a name='Resizing and Rotation'></a><br />
<h3>Resizing and Rotation</h3>
<p>What else can we do with the image once we&#8217;ve loaded it into memory with imagecreatefromjpeg()? Let&#8217;s try resizing the image. Here we will make use of the imagecreatetruecolor() function to create a blank GD resource to copy the resized image into, and the imagecopyresampled() function to perform the copying.</p>
<p>The arguments for imagecopyresampled() are as follows</p>

<div class="wp_syntax"><div class="code"><pre class="text">bool imagecopyresampled  ( resource $dst_image, resource $src_image, int $dst_x, int $dst_y, int $src_x, int $src_y, int $dst_w, int $dst_h, int $src_w, int $src_h )</pre></div></div>

<p>Which might need a little explanation: The first two are relatively straightforward, $dst_image is the GD resource to copy to, and $src_image is the GD resource to copy from. After these two arguments are 8 parameters that specify (x, y) co-ordinates on both the source and destination images, and width and height values for the source and destination images also.</p>
<p>These points and widths are used to calculate which area of the source image is to be copied based on the top-left (x, y) co-ordinates and the source width and height, and the new width and height of the destination image, as well as the top-left co-ordinate values for the new image to start at</p>
<p>When we call imagecreatetruecolor() we must also specify a width and height for this destination image.</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #990000;">header</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Content-Type: image/jpeg&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$image</span> <span style="color: #339933;">=</span> <span style="color: #339933;">@</span>imagecreatefromjpeg<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;puppy.jpg&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$size</span> <span style="color: #339933;">=</span> <span style="color: #990000;">getimagesize</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;puppy.jpg&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$percent</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">150</span><span style="color: #339933;">/</span><span style="color: #cc66cc;">100</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$image_dest</span> <span style="color: #339933;">=</span> <span style="color: #339933;">@</span>imagecreatetruecolor<span style="color: #009900;">&#40;</span><span style="color: #000033;">$size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">*</span><span style="color: #000033;">$percent</span><span style="color: #339933;">,</span> <span style="color: #000033;">$size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">*</span><span style="color: #000033;">$percent</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
imagecopyresampled<span style="color: #009900;">&#40;</span><span style="color: #000033;">$image_dest</span><span style="color: #339933;">,</span> <span style="color: #000033;">$image</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #000033;">$size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">*</span><span style="color: #000033;">$percent</span><span style="color: #339933;">,</span> <span style="color: #000033;">$size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">*</span><span style="color: #000033;">$percent</span><span style="color: #339933;">,</span> <span style="color: #000033;">$size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #000033;">$size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
imagejpeg<span style="color: #009900;">&#40;</span><span style="color: #000033;">$image_dest</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This will output an image 150% the width and height of the original. You can control the size of the image by changing the value of $percent. With some experimentation you can also try changing the ratio of the width and height to distort the image, and change the values within imagecopyresampled() to change the portion of the image that is resized.</p>
<p>Why not try image rotation by replacing the imagejpeg($image_dest); function call to the following</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #666666; font-style: italic;">// 0x000000 is the background colour to use for the blank</span>
<span style="color: #666666; font-style: italic;">// space left after the rotation calculation</span>
<span style="color: #000033;">$rotate</span> <span style="color: #339933;">=</span> imagerotate<span style="color: #009900;">&#40;</span><span style="color: #000033;">$image_dest</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">45.0</span><span style="color: #339933;">,</span> 0x000000<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
imagejpeg<span style="color: #009900;">&#40;</span><span style="color: #000033;">$rotate</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p><a href="http://www.roughguidetophp.com/wp-content/uploads/2008/08/rotate.jpg"><img class="size-medium wp-image-245" title="rotate" src="http://www.roughguidetophp.com/wp-content/uploads/2008/08/rotate-300x300.jpg" alt="Cute puppy has been rotated 45 degrees. Poor thing" width="300" height="300" /></a>
<p class="wp-caption-text">Cute puppy has been rotated 45 degrees. Poor thing</p>
<p><a name='Saving the Image To Disk'></a><br />
<h3>Saving the Image To Disk</h3>
<p>Once you&#8217;ve manipulated the image enough, you may then want to save it to disk. A common usage for such a function is the use of generated thumbnail images for image upload sites. The idea being that a user would upload an image to a forum, or an image hosting site, and they would be given the option of either linking to the full-size image, or to a small thumbnail of the image.</p>
<p>Such functionality is easy to achieve with the GD2 library, we simply modiy to the code from earlier by adding a new parameter to imagejpeg. This simply saves the GD resource to a file on the disk, as specified by the name given.</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$image</span> <span style="color: #339933;">=</span> <span style="color: #339933;">@</span>imagecreatefromjpeg<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;puppy.jpg&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$size</span> <span style="color: #339933;">=</span> <span style="color: #990000;">getimagesize</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;puppy.jpg&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// let's save a 33% thumbnail</span>
<span style="color: #000033;">$percent</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">33</span><span style="color: #339933;">/</span><span style="color: #cc66cc;">100</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$image_dest</span> <span style="color: #339933;">=</span> <span style="color: #339933;">@</span>imagecreatetruecolor<span style="color: #009900;">&#40;</span><span style="color: #000033;">$size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">*</span><span style="color: #000033;">$percent</span><span style="color: #339933;">,</span> <span style="color: #000033;">$size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">*</span><span style="color: #000033;">$percent</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
imagecopyresampled<span style="color: #009900;">&#40;</span><span style="color: #000033;">$image_dest</span><span style="color: #339933;">,</span> <span style="color: #000033;">$image</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #000033;">$size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">*</span><span style="color: #000033;">$percent</span><span style="color: #339933;">,</span> <span style="color: #000033;">$size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">*</span><span style="color: #000033;">$percent</span><span style="color: #339933;">,</span> <span style="color: #000033;">$size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #000033;">$size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// modify this final line to add an extra parameter to imagejpeg</span>
imagejpeg<span style="color: #009900;">&#40;</span><span style="color: #000033;">$image_dest</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;puppy_thumb.jpg&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p><a href="http://www.roughguidetophp.com/wp-content/uploads/2008/08/thumb1.jpg"><img class="size-medium wp-image-248" title="thumb1" src="http://www.roughguidetophp.com/wp-content/uploads/2008/08/thumb1-300x162.jpg" alt="New, smaller thumbnail puppy" width="300" height="162" /></a>
<p class="wp-caption-text">New, smaller thumbnail puppy</p>
<p>This then results in a new file on the disk, smaller in size and dimensions than the original called &#8220;puppy_thumb.jpg&#8221;. The original file is not overwritten or modified during this action. We have also removed the header() function call from the first line, since we will no longer be writing the image data to the browser window.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.roughguidetophp.com/php-image-manipulation-with-gd2/feed/</wfw:commentRss>
		</item>
		<item>
		<title>PHP Syntax</title>
		<link>http://www.roughguidetophp.com/php-syntax/</link>
		<comments>http://www.roughguidetophp.com/php-syntax/#comments</comments>
		<pubDate>Tue, 30 Nov 1999 00:00:00 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[


Saving a PHP file
A PHP file is basically a text file containing all the required PHP code to run a specific program.  PHP code can be written with the use of a simple text editor, like Windows Notepad, or the more useful Crimson Editor. All you need to do is type in the required [...]]]></description>
			<content:encoded><![CDATA[<p><!--pagetitle:Structure of a basic PHP file-->
</p>
<p><a name='Saving a PHP file'></a><br />
<h3>Saving a PHP file</h3>
<p>A PHP file is basically a text file containing all the required PHP code to run a specific program.  PHP code can be written with the use of a simple text editor, like Windows Notepad, or the more useful <a href="http://www.crimsoneditor.com/">Crimson Editor</a>. All you need to do is type in the required PHP code and save the file with the extension .php</p>
<p>You can create a PHP file yourself by creating a blank text file and simply renaming it with the extension .php. You need absolutely nothing else for this to work as a valid PHP file. Although, as I&#8217;m sure you&#8217;ll realise, a blank file won&#8217;t do anything much of use!  First of all, we need to enter some valid PHP code into this file</p>
<p>(Important: Don&#8217;t use a program such as Microsoft Word, Frontpage or other more complex word processors to create your PHP file. Although the page might look free of formatting when you save the file, there will be other hidden formatting elements within the file itself that will prevent any PHP code from running.)</p>
<p>This is an example of some PHP code</p>

<div class="wp_syntax"><div class="code"><pre class="php">&nbsp;</pre></div></div>

<p>This code is the exact same code that will work as a PHP file on a server, and we&#8217;ll take a look shortly at how you can create your very own simple PHP file to run as a basic web-page sample. First though, we need to know where to locate our PHP files.</p>
<p><a name='The location of the PHP file on disk'></a><br />
<h3>The location of the PHP file on disk</h3>
<p>An important thing for us at this point is to know where to save this .php file for it to be recognised as a valid web-page file. Any PHP documents must be placed within the document root of a website server. In simple terms, this means that on your computer, or on the remote computer that you&#8217;ve got set up as a website host, are a number of folders and directories. One of these directories will be set up as the document root, and is usually named c:local if you&#8217;re using your own Windows machine to run the code, or something like /htdocs or /html_root if you&#8217;re running on a remote server.</p>
<p>The document root is the base directory from which all the website data is served from. Any sub-directories within this main root directory will show up as sub-folders when you type in the URL</p>
<p>e.g. if you have a folder &#8220;mysite&#8221; within the c:local folder, you&#8217;ll be able to access the URL http://localhost/mysite to see the contents of this folder. Any PHP files within this folder can be accessed by adding the PHP filename to the end. e.g. http://localhost/mysite/myphpfile.php</p>
<p>Similarly with a remote host, a folder like htdocs/mysite will be accessible from http://www.mywebsite.com/mysite and any relevant PHP files in the mysite folder will be at http://www.mywebsite.com/mysite/myphpfile.php and so on</p>
<p><a name='Index.php'></a><br />
<h3>Index.php</h3>
<p>PHP files can be named anything you want, according to the filename rules of the operating system you&#8217;re using (For example, Windows filenames can&#8217;t contain certain characters) - you can have &#8220;myphpfile.php&#8221;, &#8220;biscuits.php&#8221;, &#8220;cheese_on_toast.php&#8221;. But a useful name for a PHP file is index.php</p>
<p>The reason behind naming a php file index.php is that the file &#8220;index.php&#8221; will always be loaded first when visiting a URL that doesn&#8217;t specify a filename e.g. http://www.mywebsite.com - in this case, that URL will automatically look for a file named http://www.mywebsite.com/index.php. This is an extremely useful way of defining a main page, or home page for your site.</p>
<p>In the next section, we&#8217;ll make a start on generating our first PHP file, and seeing the results in a browser window.</p>
<p><a name='Adding your first few lines of code'></a><br />
<h3>Adding your first few lines of code</h3>
<p>After saving a blank PHP file in your chosen location, point your browser to the URL where your file is located, according to the directory structure and the location you saved the file in. E.g. using the address http://localhost/myphp/myphp.php if you saved the file in c:localmyphpmyphp.php or http://www.mywebsite.com/mysite/file.php if you saved the file file.php on a remote server in the folder mysite).</p>
<p>After entering this URL, you should see a blank screen appear. This is because we&#8217;ve not added anything to the file yet!</p>
<p>Return to your text editor, and add the following lines to the file</p>

<div class="wp_syntax"><div class="code"><pre class="php">&nbsp;</pre></div></div>

<p>Type it out exactly as it&#8217;s written above. I&#8217;ll explain the symbols used here in just a moment, but return to the web browser now, and reload the page. You&#8217;ll see the following output</p>

<div class="wp_syntax"><div class="code"><pre class="php">Hello world</pre></div></div>

<p>If you see the above text, then everything is going well! You should now have your first working PHP application. If you don&#8217;t see the text above appear on the screen, go back and check the file again. You must enter the code exactly as it appears above. Now, I shall explain what&#8217;s going on here</p>
<p>The &lt;?php and ?&gt; tags are the PHP delimeters. They are used to declare where the PHP code starts, and where it ends. This will be of more importance in the next tutorial which deals with the combination of HTML code and PHP. For now, all you need to know is that these symbols are vital to the execution of the code. It is also acceptable to start and stop these PHP delimiters as often as you like. So, for example, the following code is perfectly valid
</p>

<div class="wp_syntax"><div class="code"><pre class="php">&nbsp;</pre></div></div>

<p>Note that you can also use the symbolds &lt;? and ?&gt; to express the beginning and end of the code, but the use of &lt;?php and ?&gt; is much more widely accepted as the standard, due to the way most servers interpret the code.</p>
<p>On the second line, you will see a commonly used PHP command, &#8220;echo&#8221;, which we&#8217;ll look at again later. For now, the important thing to note is the semicolon used at the end of the line. It is absolutely vital, in PHP, to terminate any expression or command with this semicolon, otherwise the code will fail.</p>
<p>If you&#8217;re coming from an ASP background (another language similar to PHP, not as widely used but still very popular) you can enable PHP to recognise ASP style tags, like so</p>

<div class="wp_syntax"><div class="code"><pre class="asp">&nbsp;</pre></div></div>

<p><a name='Using Comments in PHP'></a><br />
<h3>Using Comments in PHP</h3>
<p>Comments are an excellent way to document your code. They allow for a way to place handy notes and thoughts for yourself alongside your code so that you can pick up where you left off when you return to either add new features or debug the script. Comments also provide an effective way for other developers to understand your thoughts and motivations when working on your code.</p>
<p>Comments can be written in one of three ways as the following examples demonstrate</p>

<div class="wp_syntax"><div class="code"><pre class="php">&nbsp;</pre></div></div>

<p>Comments may seem a bit counterintuitive at first. If you&#8217;re not used to programming, you might wonder what the point is of adding all that extra work if it does nothing useful. In time though, and with experience of larger projects, you&#8217;ll find that all those little thoughts and statements become invaluable when you return to debug code days, weeks, months or years later.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.roughguidetophp.com/php-syntax/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Reporting and handling errors in PHP</title>
		<link>http://www.roughguidetophp.com/reporting-and-handling-errors-in-php/</link>
		<comments>http://www.roughguidetophp.com/reporting-and-handling-errors-in-php/#comments</comments>
		<pubDate>Tue, 30 Nov 1999 00:00:00 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[Advanced PHP]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[
When developing a PHP project, whether it&#8217;s a simple website or a much larger web application, it&#8217;s always a good idea to take into account the potential appearance of errors in your PHP code.  An error occurs whenever PHP tries to execute an instruction which either results in an impossible outcome, or otherwise prevents [...]]]></description>
			<content:encoded><![CDATA[<p><!--pagetitle:Types of Errors in PHP--></p>
<p>When developing a PHP project, whether it&#8217;s a simple website or a much larger web application, it&#8217;s always a good idea to take into account the potential appearance of errors in your PHP code.  An error occurs whenever PHP tries to execute an instruction which either results in an impossible outcome, or otherwise prevents the script from executing in the manner intended by the programmer.</p>
<p>Errors range from simple fatal errors, where program execution is halted at the point of the fault - usually a syntax error or a call to a function that doesn&#8217;t exist - to more complex errors where the cause of the problem isn&#8217;t immediately clear, and an indepth review of the code must be carried out to pinpoint the flaw.</p>
<p><a name='Undefined Variables (and other little glitches)'></a><br />
<h3>Undefined Variables (and other little glitches)</h3>
<p>Dealing with errors in a meaningful and graceful manner is a major consideration when developing PHP code. The default behaviour of PHP when encountering an error is to output a very simple line of text, with very basic formatting. It&#8217;s really quite ugly, and not the sort of thing you want your visitors to be seeing:</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #990000;">echo</span> <span style="color: #009900;">&#40;</span><span style="color: #000033;">$hello_world</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Here, we are trying to access a variable $hello_world which has not been defined. The resulting output will be a screen with the following text</p>

<div class="wp_syntax"><div class="code"><pre class="text">Notice: Undefined variable: hello_world in C:localmyphp.php on line 5</pre></div></div>

<p>Note:  You might not see this appear on screen right away. PHP sometimes is not fully set up to display all errors as they happen. To change PHP&#8217;s default behaviour, add the following lines before the echo statement above</p>
<pre class="php">error_reporting&#40;E_ALL|E_STRICT&#41;;
ini_set&#40;&quot;display_errors&quot;, TRUE&#41;;</pre>
<p>Line 1 tells PHP to report all errors (including &#8220;strict&#8221; errors, which aren&#8217;t included as part of the E_ALL argument). Line 2 sets a PHP configuration variable which instructs PHP to always display errors. This value is also hidden away in the php.ini configuration file, but that&#8217;s not always accessible, so this way of setting it is perfectly valid.</p>
<p>One way to get around this error message cropping up in the first place is to make sure you&#8217;ve properly defined the variable before you use it. And if you&#8217;re uncertain whether or not the variable is defined, you can always place checks before calling it, like so</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #666666; font-style: italic;">//the isset function checks if a given variable is defined or not</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$hello_world</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #990000;">echo</span> <span style="color: #000033;">$hello_world</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;The variable 'hello world' couldn't be located&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>But that&#8217;s not terribly practical when you have to do the same checks for every variable, and the error message displayed still makes it all too clear to the visiting public that something&#8217;s gone wrong.</p>
<p>In the next section, we will look at ways of handling these error messages in a much more efficient manner</p>
]]></content:encoded>
			<wfw:commentRss>http://www.roughguidetophp.com/reporting-and-handling-errors-in-php/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Variables in PHP</title>
		<link>http://www.roughguidetophp.com/variables-in-php/</link>
		<comments>http://www.roughguidetophp.com/variables-in-php/#comments</comments>
		<pubDate>Tue, 30 Nov 1999 00:00:00 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[
Variables are probably one of the most commonly used code constructs you&#8217;ll come across while programming. If you have any experience of mathematics, especially algebra, you&#8217;ll be aware of the concept of using symbols to represent unknown quantities in equations, like in the following example

x + 5 = 7;
from this we can deduce that x [...]]]></description>
			<content:encoded><![CDATA[<p><!--pagetitle:Introduction to variables in PHP--><br />
Variables are probably one of the most commonly used code constructs you&#8217;ll come across while programming. If you have any experience of mathematics, especially algebra, you&#8217;ll be aware of the concept of using symbols to represent unknown quantities in equations, like in the following example</p>

<div class="wp_syntax"><div class="code"><pre class="text">x + 5 = 7;
from this we can deduce that x = 2</pre></div></div>

<p>In PHP it works in a similar fashion, except we usually know the value of x, and simply assign it a specific value, such as x = 5. We can then use that value to perform calculations using other symbols and numbers. For example</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$x</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">5</span>  <span style="color: #666666; font-style: italic;">//x now equals 5</span>
<span style="color: #000033;">$y</span> <span style="color: #339933;">=</span> <span style="color: #000033;">$x</span> <span style="color: #339933;">+</span> <span style="color: #cc66cc;">10</span>  <span style="color: #666666; font-style: italic;">/* y now equals 5 + 10 */</span></pre></div></div>

<p>These symbols in PHP are known as variables and require you to follow a specific syntax to use them properly. Once you understand the principles behind them, you&#8217;ll begin to see how they form a major component of any PHP application, and can be used to store many things other than just numbers.  Let us begin though, by guiding you through a few simple examples of the use of variables.</p>
<p><a name='A simple introduction'></a><br />
<h3>A simple introduction</h3>
<p>A very simple example of the use of a variable in PHP is to hold just one number, e.g.</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$x</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">5</span><span style="color: #339933;">;</span></pre></div></div>

<p>All variables in PHP start with a dollar sign, followed by a string of numbers, letters (both lower-case and capitals) and underscores. Variables are also case sensitive, meaning that $Variable is not equal to $variable. The only other requirement of variable naming is that the first digit cannot be a number. These are examples of valid variable names</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$variable_name</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">5</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//valid - integer</span>
<span style="color: #000033;">$VariableName</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">25.5</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//valid - floating point</span>
<span style="color: #000033;">$variable3</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">155</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//valid</span>
<span style="color: #000033;">$_variable_number_four</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;value&quot;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//valid - string</span>
<span style="color: #000033;">$_x</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;five&quot;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//valid</span></pre></div></div>

<p>These are not valid variable names</p>

<div class="wp_syntax"><div class="code"><pre class="php">$1st_variable <span style="color: #339933;">=</span> <span style="color: #cc66cc;">5</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//invalid</span>
<span style="color: #000033;">$Variable</span><span style="color: #339933;">.</span>name <span style="color: #339933;">=</span> <span style="color: #cc66cc;">25</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//invalid, cannot have dots in names</span></pre></div></div>

<p>Variables are assigned values through the use of the equals sign (=) operator. Once a variable has been assigned to a value, that variable symbol can be used in place of the value anywhere in the code. The value of the variable can also be changed at any point during the execution of the code. The same value can also be assigned to multiple variables at the same time, like so</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$a</span> <span style="color: #339933;">=</span> <span style="color: #000033;">$b</span> <span style="color: #339933;">=</span> <span style="color: #000033;">$c</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">5</span><span style="color: #339933;">;</span>
<span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;$a, $b, $c&quot;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This produces the output</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #cc66cc;">5</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">5</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">5</span></pre></div></div>

<p><a name='Flexible Types'></a><br />
<h3>Flexible Types</h3>
<p>The &#8220;type&#8221; of a variable is defined by the value you&#8217;ve assigned to it. PHP supports a wide range of types, including strings, integers and floats.</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$string</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;This is a string&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$integer</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">5</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//an integer value;</span>
<span style="color: #000033;">$float</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">4.55</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//a &quot;floating point&quot; value</span></pre></div></div>

<p>PHP doesn&#8217;t explicitly require that you maintain the same type for a certain variable though. If you tried to assign a string value to a variable which previously contained an integer, you&#8217;ll encounter no problems. Similarly with any other types, floating point variables can hold integers or strings and so on.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.roughguidetophp.com/variables-in-php/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Working with dates and times in PHP</title>
		<link>http://www.roughguidetophp.com/working-with-dates-and-times-in-php/</link>
		<comments>http://www.roughguidetophp.com/working-with-dates-and-times-in-php/#comments</comments>
		<pubDate>Tue, 30 Nov 1999 00:00:00 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[Advanced PHP]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[
When developing more complex PHP sites, especially forums, discussion boards and blogs where date and time functions are important, you&#8217;ll regularly encounter situations where you need to display and manipulate values based around the current date and time. PHP includes a range of functions which can help you to easily format and adjust your date [...]]]></description>
			<content:encoded><![CDATA[<p><!--pagetitle:time(), date() and mktime()--><br />
When developing more complex PHP sites, especially forums, discussion boards and blogs where date and time functions are important, you&#8217;ll regularly encounter situations where you need to display and manipulate values based around the current date and time. PHP includes a range of functions which can help you to easily format and adjust your date and time displays to suit your needs.  In this tutorial, we&#8217;ll look at some easy ways to display calendar information for your visitors.</p>
<p><a name='time() or, the Unix Timestamp'></a><br />
<h3>time() or, the Unix Timestamp</h3>
<p>One of the simplest date/time functions in PHP is time(). This simple function takes no arguments, and simply returns a numeric value equal to the number of seconds since the &#8220;Unix Epoch&#8221;, declared as January 1st 1970 at midnight (GMT) - just an arbitrary date chosen to base timing calculations on when working with dates and times. This gives a start time upon which we can base our time calculations</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$time</span> <span style="color: #339933;">=</span> <span style="color: #990000;">time</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">echo</span> <span style="color: #000033;">$time</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//gives us something like 1219075172</span></pre></div></div>

<p><a name='PHP&#8217;s date() function'></a><br />
<h3>PHP&#8217;s date() function</h3>
<p>This timestamp can then be used as input to the date() function to format it for improved readability. The date() function takes, as its arguments, a string to define how we wish the formatted time to appear and secondly, a Unix timestamp just like the one returned by time(). It is also possible to use date() without specifying a timestamp and it will use the current time as its source.</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #990000;">echo</span> <span style="color: #990000;">date</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;F j, Y, g:i a&quot;</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">1219075172</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//produces &quot;August 18, 2008, 4:59 pm&quot;</span></pre></div></div>

<p>The string used in the date() function can contain a number of single letters which are then substituted for their human readable counterparts according to the value of the timestamp. In our case, the following substitutions are made</p>
<p>F: The full textual representation of the month, August in this case<br />
j: The day of the month, without leading zeros, e.g. 4, 18, 22<br />
Y: The full year, e.g. 2008<br />
g: The current hour, in 12-hour format<br />
i: The current number of minutes<br />
a: Either am, or pm, depending on the time</p>
<p>A full list of all the codes, and their textual counterparts can be seen on PHP.net&#8217;s date() page <a href="http://uk2.php.net/manual/en/function.date.php">here</a>. Extra text can be added to the formatted string as required, but remember to escape any characters which date() will interpret as formatting text.</p>
<p><a name='Make time with mktime()'></a><br />
<h3>Make time with mktime()</h3>
<p>An alternative to the time() function is mktime(). This function is useful when we wish to use a date/time which is not the current time. mktime() takes as its arguments numerical values representing, in this order - hours, minutes, seconds, months, days, years - and a final value to declare whether daylight savings time is to be taken into account.</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$date</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mktime</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">10</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">15</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">12</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">12</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">1980</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//produces 345464100</span>
<span style="color: #990000;">echo</span> <span style="color: #990000;">date</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;F j, Y, g:i a&quot;</span><span style="color: #339933;">,</span> <span style="color: #000033;">$date</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//produces &quot;December 12, 1980, 10:15 am&quot;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.roughguidetophp.com/working-with-dates-and-times-in-php/feed/</wfw:commentRss>
		</item>
		<item>
		<title>10 Regular Expressions you just can&#8217;t live without in PHP</title>
		<link>http://www.roughguidetophp.com/10-regular-expressions-you-just-cant-live-%20without-in-php/</link>
		<comments>http://www.roughguidetophp.com/10-regular-expressions-you-just-cant-live-%20without-in-php/#comments</comments>
		<pubDate>Tue, 30 Nov 1999 00:00:00 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<guid isPermaLink="false"></guid>
		<description><![CDATA[
Verifying a Valid UsernameVerifying Valid DatesValidating IP AddressesMatching Phone Numbers, Postcodes, Social Security numbers etcValidating Email AddressesVerifying Credit Card NumbersReplacing Static Links with Hyperlinks in HTMLRemoving Swearing and Profanity from blogs and forumsStripping out Bad Attributes and Javascript from HTML codeBBCode - Custom Formatting DefinitionsConclusion
Regular expression are one of the most powerful features of PHP. [...]]]></description>
			<content:encoded><![CDATA[<p><!--pagetitle:Handy Regular Expressions for validating data--></p>
<p><a href='#Verifying a Valid Username'>Verifying a Valid Username</a><a href='#Verifying Valid Dates'>Verifying Valid Dates</a><a href='#Validating IP Addresses'>Validating IP Addresses</a><a href='#Matching Phone Numbers, Postcodes, Social Security numbers etc'>Matching Phone Numbers, Postcodes, Social Security numbers etc</a><a href='#Validating Email Addresses'>Validating Email Addresses</a><a href='#Verifying Credit Card Numbers'>Verifying Credit Card Numbers</a><a href='#Replacing Static Links with Hyperlinks in HTML'>Replacing Static Links with Hyperlinks in HTML</a><a href='#Removing Swearing and Profanity from blogs and forums'>Removing Swearing and Profanity from blogs and forums</a><a href='#Stripping out Bad Attributes and Javascript from HTML code'>Stripping out Bad Attributes and Javascript from HTML code</a><a href='#BBCode - Custom Formatting Definitions'>BBCode - Custom Formatting Definitions</a><a href='#Conclusion'>Conclusion</a></p>
<p>Regular expression are one of the most powerful features of PHP. They&#8217;re also one of the most confusing and bewlidering if you&#8217;re not familiar with their syntax. They can be used for a wide range of purposes, from validating user names to grabbing data from a website. In this article, I&#8217;ll take you through 10 regular expression functions which I have found extremely useful in the past and which can play an important role in any modern website or application.</p>
<p><a name='Verifying a Valid Username'></a><br />
<h3>Verifying a Valid Username</h3>
<p><a href='#top'>^Back to top</a></p>
<p>Sometimes we need to impose rules on a website about what sort of names a user can choose. For our own needs, and for readability, it&#8217;s often useful to state rules which force users to choose names containing only letters, numbers or underscores.</p>
<p>The following regular expression function checks a given username string based on the following rules</p>
<p>A username must start with a lower-case or upper-case letter<br />
A username can contain only letters, numbers or underscores<br />
A username must be between 8 and 24 characters<br />
A username cannot end in an underscore</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">function</span> valid_name<span style="color: #009900;">&#40;</span><span style="color: #000033;">$username</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #990000;">preg_match</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;#^[a-z][da-z_]{6,22}[a-zd]$#i&quot;</span><span style="color: #339933;">,</span> <span style="color: #000033;">$username</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$usernames</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
  <span style="color: #0000ff;">&quot;RoughGuide98&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;_invalidUsername&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;%423f@''#&quot;</span><span style="color: #339933;">,</span>  <span style="color: #0000ff;">&quot;25UserName&quot;</span><span style="color: #339933;">,</span>
  <span style="color: #0000ff;">&quot;I_am_valid_user&quot;</span><span style="color: #339933;">,</span>  <span style="color: #0000ff;">&quot;I am not a valid user&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;tooshort&quot;</span><span style="color: #339933;">,</span>
  <span style="color: #0000ff;">&quot;ThisUserNameIsTooLongAndWontBeAccepted&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;ThisIsTheRightSize&quot;</span>
  <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 
<span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000033;">$usernames</span> <span style="color: #b1b100;">as</span> <span style="color: #000033;">$name</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>valid_name<span style="color: #009900;">&#40;</span><span style="color: #000033;">$name</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;$name - Ok&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">else</span>
        <span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;$name - Unsuitable!&quot;</span><span style="color: #339933;">;</span>  
<span style="color: #009900;">&#125;</span>
 
<span style="color: #666666; font-style: italic;">/* This produces...
RoughGuide98 - Ok
_invalidUsername - Unsuitable!
%423f@''# - Unsuitable!
25UserName - Unsuitable!
I_am_valid_user - Ok
I am not a valid user - Unsuitable!
short - Unsuitable!
ThisUserNameIsTooLongAndWontBeAccepted - Unsuitable!
ThisIsTheRightSize - Ok */</span></pre></div></div>

<p><a name='Verifying Valid Dates'></a><br />
<h3>Verifying Valid Dates</h3>
<p><a href='#top'>^Back to top</a></p>
<p>This regular expression function will check if a date provided is valid in the DD-MM-YYYY format and can successfully check for an incorrect date value for specific months. It will also deal successfully with February 29th on leap years. It can accept the characters &#8220;/&#8221;, &#8220;-&#8221; and &#8220;.&#8221; as date seperators.</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">function</span> check_date<span style="color: #009900;">&#40;</span><span style="color: #000033;">$date</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #000033;">$seperator</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;[/-.]&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #990000;">preg_match</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;#^(((0?[1-9]|1d|2[0-8]){$seperator}(0?[1-9]|1[012])|(29|30){$seperator}(0?[13456789]|1[012])|31{$seperator}(0?[13578]|1[02])){$seperator}(19|[2-9]d)d{2}|29{$seperator}0?2{$seperator}((19|[2-9]d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$#&quot;</span><span style="color: #339933;">,</span> <span style="color: #000033;">$date</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">==</span><span style="color: #cc66cc;">1</span>?<span style="color: #000000; font-weight: bold;">true</span><span style="color: #339933;">:</span><span style="color: #000000; font-weight: bold;">false</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Here&#8217;s the function in action</p>

<div class="wp_syntax"><div class="code"><pre class="php">check_date<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;30.9.2005&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//valid</span>
check_date<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;32.9.2005&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//invalid</span>
check_date<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;29.1.2005&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//valid</span>
check_date<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;29.2.2005&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//invalid</span></pre></div></div>

<p><a name='Validating IP Addresses'></a><br />
<h3>Validating IP Addresses</h3>
<p><a href='#top'>^Back to top</a></p>
<p>This regular expression function will check if a given IP address is within the valid range, specifically between 0.0.0.0 and 255.255.255.255</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">function</span> valid_ip<span style="color: #009900;">&#40;</span><span style="color: #000033;">$ip_address</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #000033;">$val_0_to_255</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;(25[012345]|2[01234]d|[01]?dd?)&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #000033;">$pattern</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;#^($val_0_to_255.$val_0_to_255.$val_0_to_255.$val_0_to_255)$#&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #990000;">preg_match</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$pattern</span><span style="color: #339933;">,</span> <span style="color: #000033;">$ip_address</span><span style="color: #339933;">,</span> <span style="color: #000033;">$matches</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This regular expression is relatively simple. It uses the regular expression to find a number between 0 and 255 and repeats it 4 times, seperated by dots. Here&#8217;s the function in use</p>

<div class="wp_syntax"><div class="code"><pre class="php">valid_ip<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;0.0.0.255&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//valid</span>
valid_ip<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;0.0.0.256&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//invalid</span></pre></div></div>

<p><a name='Matching Phone Numbers, Postcodes, Social Security numbers etc'></a><br />
<h3>Matching Phone Numbers, Postcodes, Social Security numbers etc</h3>
<p><a href='#top'>^Back to top</a></p>
<p>All of these are fairly similar, so are lumped into the same category here. I&#8217;ve left out &#8220;Credit Card Numbers&#8221; since they can require a little extra consideration, and I&#8217;ve given them their own section later on. But for now, let&#8217;s look at how we can use pattern matching to check some of the most common number sequences we use in our daily lives.</p>
<p>Let&#8217;s look first at matching a valid US telephone number</p>
<p>US phone numbers are of the format 000 000 0000, a group of three numbers, followed by another three then a final four. We can write this in regular expression format as follows</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$reg</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;#^d{3}sd{3}sd{4}$#&quot;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This will match any phone number in the above format, like 351 234 5555. But we run into problems if we&#8217;re using a different notation, like (123)-555-5555. No worries though, the following alterations will allow us to use all sorts of variations like this</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$reg</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;#^(?d{3})?[s.-]?d{3}[s.-]?d{4}$#&quot;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Let&#8217;s try this now</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">function</span> matchUSPhone<span style="color: #009900;">&#40;</span><span style="color: #000033;">$number</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000033;">$reg</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;#^(?d{3})?[s.-]?d{3}[s.-]?d{4}$#&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">return</span> <span style="color: #990000;">preg_match</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$reg</span><span style="color: #339933;">,</span> <span style="color: #000033;">$number</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
 
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span>matchUSPhone<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;(123)-555-5555&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;This matches&quot;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">//indeed, this does match</span></pre></div></div>

<p>Here&#8217;s some other useful functions you can use</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #666666; font-style: italic;">//Match a UK format phone number</span>
<span style="color: #000000; font-weight: bold;">function</span> matchUKPhoneNumber<span style="color: #009900;">&#40;</span><span style="color: #000033;">$number</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">//UK Phone numbers are 10 or 11 digits long, and have a 3, 4, 5 or 6 digit area code</span>
  <span style="color: #000033;">$s</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;(([ -.])*)?&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #000033;">$result</span> <span style="color: #339933;">=</span> <span style="color: #990000;">preg_match</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;#^(((?d{3})?$sd{7,8})|((?d{4})?$sd{6,7})|((?d{5})?$sd{5,6})|((?d{6})?$sd{4,5}))$#&quot;</span><span style="color: #339933;">,</span> <span style="color: #000033;">$number</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">return</span> <span style="color: #000033;">$result</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
 
<span style="color: #666666; font-style: italic;">//Match a US social security number</span>
<span style="color: #000000; font-weight: bold;">function</span> matchUSSocialSecurity<span style="color: #009900;">&#40;</span><span style="color: #000033;">$ss_num</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">return</span> <span style="color: #990000;">preg_match</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;#d{3}-d{2}-d{4}#&quot;</span><span style="color: #339933;">,</span> <span style="color: #000033;">$ss_num</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
 
<span style="color: #666666; font-style: italic;">//This regular expression matches a UK National Insurance number  </span>
<span style="color: #000000; font-weight: bold;">function</span> matchUKNationalInsurance<span style="color: #009900;">&#40;</span><span style="color: #000033;">$ni</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #000033;">$digits_1_and_2</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;[ABCEGHJKLMNOPRSTWXYZ][ABCEGHJKLMNPRSTWXYZ]&quot;</span><span style="color: #339933;">;</span>  
  <span style="color: #000033;">$the_rest</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;d{6}[A-D]?&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #000033;">$reg</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;#^&quot;</span><span style="color: #339933;">.</span><span style="color: #000033;">$digits_1_and_2</span><span style="color: #339933;">.</span><span style="color: #000033;">$the_rest</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;$#&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">return</span> <span style="color: #990000;">preg_match</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$reg</span><span style="color: #339933;">,</span> <span style="color: #000033;">$ni</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><a name='Validating Email Addresses'></a><br />
<h3>Validating Email Addresses</h3>
<p><a href='#top'>^Back to top</a></p>
<p>Checking that an email address is valid is a fairly tricky thing. You have to make sure the domain name is correct, and that the first part of the email contains valid characters. Using regular expressions though, something like this becomes fairly trivial. Here&#8217;s a simple example to match a very basic email address</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$reg</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;#(.*)@(.*).com#&quot;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This is pretty useless though, since it will only match email addresses ending in &#8220;.com&#8221;. A more concrete example is as follows</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">function</span> checkEmail<span style="color: #009900;">&#40;</span><span style="color: #000033;">$email</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #000033;">$reg</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;#^(((([a-zd][.-+_]?)*)[a-z0-9])+)@(((([a-zd][.-_]?){0,62})[a-zd])+).([a-zd]{2,6})$#i&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #990000;">preg_match</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$reg</span><span style="color: #339933;">,</span> <span style="color: #000033;">$email</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>   
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>And a couple of examples</p>

<div class="wp_syntax"><div class="code"><pre class="php">checkEmail<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;robin@roughguidetophp.com&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//valid</span>
checkEmail<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;not-an-email@address&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//invalid</span></pre></div></div>

<p>Note that this function won&#8217;t determine whether a given email address actually exists and is valid. To achieve that, you&#8217;d need to implement more checks. One possibility is to use the PHP function checkdnsrr() to check that the domain name is valid, although that only exists on Unix installations of PHP. On Windows you&#8217;d need to write your own custom function.</p>
<p>You would then still need to check that the mailbox itself exists, which could be achieved by sending out a confirmation email to the user, and if they receive it, and click on the link contained within, then you&#8217;ll know it&#8217;s a valid address.</p>
<p><a name='Verifying Credit Card Numbers'></a><br />
<h3>Verifying Credit Card Numbers</h3>
<p><a href='#top'>^Back to top</a></p>
<p>When developing e-commerce applications, it becomes necessary to process credit card details, and make sure they&#8217;re accurate. A simple check you can perform is to see if the credit card number a customer provides fits the card number definitions laid out by the card issuers. For example, a Visa card number starts with a 4, and can contain 16 or 13 digits. </p>
<p>The following regular expression function will check to see if a card number conforms to the appropriate rules. This function checks for some of the most common card types. An additional second parameter can be entered to use a Luhn algorithm check<a href='#fn-467-1' id='fnref-467-1'>1</a> which is a method used by card issuers to generate valid card numbers, as opposed to random strings of digits. Read more about the <a target="_blank" href="http://en.wikipedia.org/wiki/Luhn_algorithm">Luhn algorithm at Wikipedia</a>, if you&#8217;re interested</p>
<p>check_cc() will return false if the card number isn&#8217;t valid and if it is valid, will return a string containing the type of card matched.</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">function</span> validatecard<span style="color: #009900;">&#40;</span><span style="color: #000033;">$cardnumber</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000033;">$cardnumber</span><span style="color: #339933;">=</span><span style="color: #990000;">preg_replace</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;/D|s/&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">,</span> <span style="color: #000033;">$cardnumber</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  <span style="color: #666666; font-style: italic;"># strip any non-digits</span>
    <span style="color: #000033;">$cardlength</span><span style="color: #339933;">=</span><span style="color: #990000;">strlen</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$cardnumber</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000033;">$parity</span><span style="color: #339933;">=</span><span style="color: #000033;">$cardlength</span> <span style="color: #339933;">%</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">;</span>
    <span style="color: #000033;">$sum</span><span style="color: #339933;">=</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000033;">$i</span><span style="color: #339933;">=</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> <span style="color: #000033;">$i9</span><span style="color: #009900;">&#41;</span> <span style="color: #000033;">$digit</span><span style="color: #339933;">=</span><span style="color: #000033;">$digit</span><span style="color: #cc66cc;">-9</span><span style="color: #339933;">;</span>
      <span style="color: #000033;">$sum</span><span style="color: #339933;">=</span><span style="color: #000033;">$sum</span><span style="color: #339933;">+</span><span style="color: #000033;">$digit</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000033;">$valid</span><span style="color: #339933;">=</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$sum</span><span style="color: #339933;">%</span><span style="color: #cc66cc;">10</span><span style="color: #339933;">==</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #000033;">$valid</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
 
 
<span style="color: #000000; font-weight: bold;">function</span> check_cc<span style="color: #009900;">&#40;</span><span style="color: #000033;">$cc</span><span style="color: #339933;">,</span> <span style="color: #000033;">$extra_check</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #000033;">$cards</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
        <span style="color: #0000ff;">&quot;visa&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;(4d{12}(?:d{3})?)&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #0000ff;">&quot;amex&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;(3[47]d{13})&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #0000ff;">&quot;jcb&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;(35[2-8][89]ddd{10})&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #0000ff;">&quot;maestro&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;((?:5020|5038|6304|6579|6761)d{12}(?:dd)?)&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #0000ff;">&quot;solo&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;((?:6334|6767)d{12}(?:dd)?d?)&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #0000ff;">&quot;mastercard&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;(5[1-5]d{14})&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #0000ff;">&quot;switch&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;(?:(?:(?:4903|4905|4911|4936|6333|6759)d{12})|(?:(?:564182|633110)d{10})(dd)?d?)&quot;</span><span style="color: #339933;">,</span>
    <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000033;">$names</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Visa&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;American Express&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;JCB&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;Maestro&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;Solo&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;Mastercard&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;Switch&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000033;">$matches</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000033;">$pattern</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;#^(?:&quot;</span><span style="color: #339933;">.</span><span style="color: #990000;">implode</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;|&quot;</span><span style="color: #339933;">,</span> <span style="color: #000033;">$cards</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;)$#&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #000033;">$result</span> <span style="color: #339933;">=</span> <span style="color: #990000;">preg_match</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$pattern</span><span style="color: #339933;">,</span> <span style="color: #990000;">str_replace</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot; &quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">,</span> <span style="color: #000033;">$cc</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #000033;">$matches</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$extra_check</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #000033;">$result</span> <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        <span style="color: #000033;">$result</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>validatecard<span style="color: #009900;">&#40;</span><span style="color: #000033;">$cc</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>?<span style="color: #cc66cc;">1</span><span style="color: #339933;">:</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #009900;">&#40;</span><span style="color: #000033;">$result</span><span style="color: #339933;">&gt;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span>?<span style="color: #000033;">$names</span><span style="color: #009900;">&#91;</span><span style="color: #990000;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$matches</span><span style="color: #009900;">&#41;</span><span style="color: #cc66cc;">-2</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">:</span><span style="color: #000000; font-weight: bold;">false</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>And here&#8217;s a sample of the function in action</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$cards</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
    <span style="color: #0000ff;">&quot;4111 1111 1111 1111&quot;</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">&quot;4111 1111 1111 1&quot;</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">&quot;4111 1111 1111 111&quot;</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">&quot;3400 0000 0000 009&quot;</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">&quot;3500 0000 0000 009&quot;</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">&quot;5500 1545 0000 0004&quot;</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">&quot;5940 0000 0000 0004&quot;</span>
<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 
<span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$cards</span> <span style="color: #b1b100;">as</span> <span style="color: #000033;">$c</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #000033;">$check</span> <span style="color: #339933;">=</span> check_cc<span style="color: #009900;">&#40;</span><span style="color: #000033;">$c</span><span style="color: #339933;">,</span> <span style="color: #000000; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$check</span><span style="color: #339933;">!==</span><span style="color: #000000; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span>
        <span style="color: #990000;">echo</span> <span style="color: #000033;">$c</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot; - &quot;</span><span style="color: #339933;">.</span><span style="color: #000033;">$check</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">else</span>
        <span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;$c - Not a match&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #990000;">echo</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
 
<span style="color: #666666; font-style: italic;">/*
This gives us
4111 1111 1111 1111 - Visa
4111 1111 1111 1 - Visa
4111 1111 1111 111 - Not a match
3400 0000 0000 009 - American Express
3500 0000 0000 009 - Not a match
5500 1545 0000 0004 - Mastercard
5940 0000 0000 0004 - Not a match
 
Using the Luhn algorithm, we can also check further to 
see if any of these numbers actually represents a valid card
check_cc(&quot;5500 1545 0000 0004&quot;, true); //matches
check_cc(&quot;5500 1585 0000 0004&quot;, true); //doesn't match
 
*/</span></pre></div></div>

<p><a name='Replacing Static Links with Hyperlinks in HTML'></a><br />
<h3>Replacing Static Links with Hyperlinks in HTML</h3>
<p><a href='#top'>^Back to top</a></p>
<p>A useful feature on most forums is the ability to type in a website address, like http://www.google.com, for example, and have that address automatically linked, via a HTML hyperlink, like so - <a href="http://www.google.com">http://www.google.com</a>. The following regular expression function will automatically replace any website addresses with the appropriate HTML code to produce an active link</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">function</span> replace_urls<span style="color: #009900;">&#40;</span><span style="color: #000033;">$string</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #000033;">$host</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;([a-zd][-a-zd]*[a-zd].)+[a-z][-a-zd]*[a-z]&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #000033;">$port</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;(:d{1,})?&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #000033;">$path</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;(/[^?#&quot;</span>s<span style="color: #009900;">&#93;</span><span style="color: #339933;">+</span><span style="color: #009900;">&#41;</span>?<span style="color: #0000ff;">&quot;;
    $query = &quot;</span><span style="color: #009900;">&#40;</span>?<span style="color: #009900;">&#91;</span>^<span style="color: #666666; font-style: italic;">#&quot;s]+)?&quot;;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #990000;">preg_replace</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;#((ht|f)tps?://{$host}{$port}{$path}{$query})#i&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;$1&quot;</span><span style="color: #339933;">,</span> <span style="color: #000033;">$string</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Here, the four different components of the average URL - host (e.g. www.google.com), port (e.g. www.website.com:8080), path (e.g. www.website.com/mysite/file.php) and the query string (e.g. www.website.com/index.php?var=1&#038;var2=100) - are combined to generate the final regular expression pattern.</p>
<p>An example of this in action</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$string</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;Visit http://www.google.com for all your searching requirements! And here are some pictures of cheese - http://images.google.co.uk/images?q=cheese&quot;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">echo</span> replace_urls<span style="color: #009900;">&#40;</span><span style="color: #000033;">$string</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 
<span style="color: #666666; font-style: italic;">/*
This produces...
Visit http://www.google.com for all your searching requirements!
And here are some pictures of cheese - http://images.google.co.uk/images?q=cheese
*/</span></pre></div></div>

<p><a name='Removing Swearing and Profanity from blogs and forums'></a><br />
<h3>Removing Swearing and Profanity from blogs and forums</h3>
<p><a href='#top'>^Back to top</a></p>
<p>Sometimes it&#8217;s useful to be able to protect the youngsters and more fragile minded members of our communities from having to see rude words on their computer screens by filtering out any words deemed to be unsuitable from any comments posted by site members.</p>
<p>The following regular expression function makes use of the preg_replace_callback() function in PHP to perform a function call &#8220;stars&#8221; on every matched instance for the words in the $swears array, replacing each letter except the first with star symbols.</p>
<p>This function can be used after retrieving data from a database, to filter out any unsuitable content.  You can also use this function to filter out any other keywords, perhaps to prevent users from advertising your competitor&#8217;s products on your forum, for example.</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">function</span> deswear<span style="color: #009900;">&#40;</span><span style="color: #000033;">$string</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
 
    <span style="color: #000000; font-weight: bold;">function</span> prep_regexp_array<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span><span style="color: #000033;">$item</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        <span style="color: #000033;">$item</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;#$item#i&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
 
    <span style="color: #000000; font-weight: bold;">function</span> stars<span style="color: #009900;">&#40;</span><span style="color: #000033;">$matches</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #990000;">substr</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$matches</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span><span style="color: #990000;">str_repeat</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;*&quot;</span><span style="color: #339933;">,</span> <span style="color: #990000;">strlen</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$matches</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #cc66cc;">-1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>    
 
    <span style="color: #000033;">$swears</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;darn&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;heck&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;blast&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;shoot&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #990000;">array_walk</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$swears</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;prep_regexp_array&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #990000;">preg_replace_callback</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$swears</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;stars&quot;</span><span style="color: #339933;">,</span> <span style="color: #000033;">$string</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>And an example of this in action</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$string</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;Aw, darn, HECK, Blast and ShOoT!&quot;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">echo</span> deswear<span style="color: #009900;">&#40;</span><span style="color: #000033;">$string</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">//Aw, d***, H***, B**** and S****!</span></pre></div></div>

<p><a name='Stripping out Bad Attributes and Javascript from HTML code'></a><br />
<h3>Stripping out Bad Attributes and Javascript from HTML code</h3>
<p><a href='#top'>^Back to top</a></p>
<p>When working with a forum or blog where user comments are welcomed, it&#8217;s often necessary to maintain strict control over exactly what a user can post on the site. The simplest method is just to strip out all unwanted content using the PHP function strip_tags(). This function also has an optional argument to let you leave certain tags in place though, like &lt;b> or &lt;u> if you wish to allow users the ability to specify custom formatting</p>
<p>A problem with this, though, is that strip_tags() will not remove whatever is inside the &lt;b> or &lt;u> tags if you leave them in place. For example, the following code will not get stripped out using strip_tags()</p>
<pre>This is &lt;b style='font-size:100px' onMouseOver='alert(&quot;Hello&quot;)'&gt;malicious text!&lt;/b&gt;</pre>
<p>This will trigger a javascript alert window whenever you move your mouse over the bold text and also - because of the &#8220;style&#8221; attribute - make the text 100 pixels tall. Not what you want to be seeing on your message board!</p>
<p>The following function will not only strip out any unwanted tags from your HTML code, but will also clean up whatever attributes are inside those tags, preventing people from messing up your page</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">function</span> cleanTags<span style="color: #009900;">&#40;</span><span style="color: #000033;">$source</span><span style="color: #339933;">,</span> <span style="color: #000033;">$tags</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">function</span> clean<span style="color: #009900;">&#40;</span><span style="color: #000033;">$matched</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
          <span style="color: #000033;">$attribs</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;javascript:|onclick|ondblclick|onmousedown|onmouseup|onmouseover|&quot;</span><span style="color: #339933;">.</span>
                     <span style="color: #0000ff;">&quot;onmousemove|onmouseout|onkeypress|onkeydown|onkeyup|&quot;</span><span style="color: #339933;">.</span>
                     <span style="color: #0000ff;">&quot;onload|class|id|src|style&quot;</span><span style="color: #339933;">;</span>
          <span style="color: #000033;">$quot</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">|</span><span style="color: #0000ff;">'|`&quot;;
          $stripAttrib = &quot;'</span> <span style="color: #009900;">&#40;</span><span style="color: #000033;">$attribs</span><span style="color: #009900;">&#41;</span>s<span style="color: #339933;">*=</span>s<span style="color: #339933;">*</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$quot</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">.*</span>?<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #0000ff;">'i&quot;;
          $clean = stripslashes($matched[0]);
          $clean = preg_replace($stripAttrib, '</span><span style="color: #0000ff;">', $clean);
          return $clean;
    }      
 
    $allowedTags='</span><span style="color: #0000ff;">';
    $clean = strip_tags($source, $allowedTags);
    $clean = preg_replace_callback('</span><span style="color: #666666; font-style: italic;">##', &quot;clean&quot;, $source);</span>
    <span style="color: #b1b100;">return</span> <span style="color: #000033;">$source</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Here&#8217;s the function in action</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$string</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;This is malicious text!&quot;</span><span style="color: #339933;">;</span>
 
<span style="color: #990000;">echo</span> <span style="color: #000033;">$string</span><span style="color: #339933;">;</span>
<span style="color: #990000;">echo</span> cleanTags<span style="color: #009900;">&#40;</span><span style="color: #000033;">$string</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">//gives us...</span>
<span style="color: #666666; font-style: italic;">//  This is malicious text!</span></pre></div></div>

<p><a name='BBCode - Custom Formatting Definitions'></a><br />
<h3>BBCode - Custom Formatting Definitions</h3>
<p><a href='#top'>^Back to top</a></p>
<p>A more comprehensive approach to the previous problem of disallowing certain tags in HTML user input is to completely strip out all tags, except for your own custom-defined ones. </p>
<p>Instead of declaring your tags using pointed brackets (< and >) you can create custom tags, most commonly with square brackets ([ and ]). This is known as BBCode (Bulletin Board Code). It is a simple way of defining custom formatting rules for forums and gives more control to the board owner over what users can and cannot do. Any range of tags can be defined, the most common of which are &#91;b] for bold, &#91;for underline and &#91;to place a link.</p>
<p>Here is a simple implementation of some basic BBCode rules</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000000; font-weight: bold;">function</span> BBcode<span style="color: #009900;">&#40;</span><span style="color: #000033;">$string</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
 
    <span style="color: #666666; font-style: italic;">//get rid of all HTML tags</span>
    <span style="color: #000033;">$string</span> <span style="color: #339933;">=</span> <span style="color: #990000;">strip_tags</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$string</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 
    <span style="color: #000033;">$patterns</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
        <span style="color: #0000ff;">&quot;bold&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;#[b](.*?)[/b]#is&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #0000ff;">&quot;italics&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;#[i](.*?)[/i]#is&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #0000ff;">&quot;underline&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;#[u](.*?)[/u]#is&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #0000ff;">&quot;link_title&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;#[url=(.*?)](.*?)[/url]#i&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #0000ff;">&quot;link_basic&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;#[url](.*?)[/url]#i&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #0000ff;">&quot;color&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;#[color=(red|green|blue|yellow)](.*?)[/color]#is&quot;</span>
    <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 
    <span style="color: #000033;">$replacements</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
        <span style="color: #0000ff;">&quot;bold&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;$1&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #0000ff;">&quot;italics&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;$1&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #0000ff;">&quot;underline&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;$1&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #0000ff;">&quot;link_title&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;$2&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #0000ff;">&quot;link_basic&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;$1&quot;</span><span style="color: #339933;">,</span>
        <span style="color: #0000ff;">&quot;color&quot;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;$2&quot;</span>
    <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 
    <span style="color: #b1b100;">return</span> <span style="color: #990000;">preg_replace</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$patterns</span><span style="color: #339933;">,</span> <span style="color: #000033;">$replacements</span><span style="color: #339933;">,</span> <span style="color: #000033;">$string</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This regular expression function searches through a given string for any instances of matching text within square brackets, followed by a matching closing pair of brackets with the same text inside. So, for example, the text &#8220;&#91;b]this is bold&#91;/b]&#8221; would be matched by the first expression in the array. Note how we&#8217;re specifying that the contents of each pair of brackets musn&#8217;t be a greedy search - denoted by the ? after the * symbol. Otherwise, a string like &#8220;&#91;b]this is bold&#91;/b] and &#91;b]this is also bold&#91;/b]&#8221; would return a match for everything within the first &#91;b] and the last &#91;/b], not what we require.</p>
<p>Here it is in action</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #990000;">echo</span> BBcode<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;[b]this is[/b] me being [b]bold[/b], and [url=http://www.google.com]here's a link[/url] and another - [url]http://www.google.com[/url]&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">//this is me being bold, and here's a link and another - http://www.google.com</span>
 
<span style="color: #990000;">echo</span> BBcode<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Here's some [color=red]Red Text![/color]&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">//Here's some Red Text!</span></pre></div></div>

<p><a name='Conclusion'></a><br />
<h3>Conclusion</h3>
<p><a href='#top'>^Back to top</a></p>
<p>So, there you go. Hopefully you&#8217;ve gained some useful knowledge from this article. At the very least, you should now have an understanding of the power of regular expressions and be able to see how they can fit in with your website applications to provide extra functionality.</p>
<p>These expressions and functions can also be translated into other programming languages fairly easily, like Javascript or Perl (Perl&#8217;s regular expression handling is actually far superior to PHP&#8217;s, and I&#8217;d recommend checking it out just to get a grasp of regular expression handling in its purest form). The expressions themselves will need very little altered when being used elsewhere, although the PHP functions used will most likely have different counterparts.</p>
<p>Try messing around with the expressions to obtain different results, and feel free to use any code in this article in your own programs.</p>
<p>Thanks to www.planzero.org  <a href='#fnref-467-1'>&#8617;</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.roughguidetophp.com/10-regular-expressions-you-just-cant-live-%20without-in-php/feed/</wfw:commentRss>
		</item>
		<item>
		<title>2008</title>
		<link>http://www.roughguidetophp.com/2008/</link>
		<comments>http://www.roughguidetophp.com/2008/#comments</comments>
		<pubDate>Tue, 30 Nov 1999 00:00:00 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<guid isPermaLink="false"></guid>
		<description><![CDATA[
]]></description>
			<content:encoded><![CDATA[<p><!--pagetitle:--></p>
]]></content:encoded>
			<wfw:commentRss>http://www.roughguidetophp.com/2008/feed/</wfw:commentRss>
		</item>
		<item>
		<title>A simple IP Address and Visitor Tracking tool with PHP &#038; MySQL</title>
		<link>http://www.roughguidetophp.com/a-simple-ip-address-and-visitor-tracking-tool-with-php-mysql/</link>
		<comments>http://www.roughguidetophp.com/a-simple-ip-address-and-visitor-tracking-tool-with-php-mysql/#comments</comments>
		<pubDate>Tue, 30 Nov 1999 00:00:00 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[PHP with MySQL]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[
(Download all the files used in this tutorial here)

Visitor Tracking and Analysis
When running a website, whether it&#8217;s a small personal homepage, or a large site for a company, it&#8217;s useful to be able to know who is visiting your site, and what they&#8217;re up to while they&#8217;re there. If you use PHP and MySQL to [...]]]></description>
			<content:encoded><![CDATA[<p><!--pagetitle:Grabbing some useful information about your visitors--></p>
<p>(Download all the files used in this tutorial <a href='http://www.roughguidetophp.com/wp-content/uploads/2008/09/visitor_tracking_php_mysql.zip'>here</a>)</p>
<p><a name='Visitor Tracking and Analysis'></a><br />
<h3>Visitor Tracking and Analysis</h3>
<p>When running a website, whether it&#8217;s a small personal homepage, or a large site for a company, it&#8217;s useful to be able to know who is visiting your site, and what they&#8217;re up to while they&#8217;re there. If you use PHP and MySQL to build your site, then it becomes a simple task to retrieve some information about your visitors and write it into the database, to be viewed at a later date. </p>
<p>Using this information, you can develop strategies to improve your website, and learn about your visitor&#8217;s browsing trends. You might even be able to tailor specific pages for a visitor&#8217;s purpose based on what search terms they used to find that page.</p>
<p><img src="http://www.roughguidetophp.com/wp-content/uploads/2008/09/iptracker.jpg" alt="Store and view useful information about all your visitors" title="iptracker" width="600" height="440" class="size-full wp-image-424" />
<p class="wp-caption-text">Store and view useful information about all your visitors</p>
<p>In this tutorial, I&#8217;ll take you through the steps required to build and install a very simple visitor tracking tool on your website, so you can start analysing your visitors behaviours.</p>
<p><a name='The files you&#8217;ll need'></a><br />
<h3>The files you&#8217;ll need</h3>
<p>During this tutorial we&#8217;ll need to create 5 files. If you&#8217;d rather just get straight to the point and try installing this application yourself, you can download all the files used in this article <a href='http://www.roughguidetophp.com/wp-content/uploads/2008/09/visitor_tracking_php_mysql.zip'>here</a></p>
<p>ip_report.php - To access and view visitor statistics<br />
ip_tracker.php - The plugin module which will update the database with the relevant values<br />
three test pages - To let you see the tool in action!<br />
session_end.php - An optional file, used during testing to manually reset a session</p>
<p>We&#8217;ll also need to create a new MySQL table, visitor_tracking, the code for that is included in the zip file, as well as in the area below.</p>
<p><a name='Considerations before we start'></a><br />
<h3>Considerations before we start</h3>
<p>Let&#8217;s consider first, what we might want to achieve using a tool like this. Basically, we want to be able to access information about our visitors. But what information? And in what format?</p>
<p>We&#8217;re going to be storing our visitor data in a MySQL database. We&#8217;re also going to put measures in place to ensure that we don&#8217;t confuse unique visits with page hits. unique visit is when one single person visits your website and when that happens, we want only one record in the database. But, we also want to see the individual page hits which show how many individual pages each person has viewed. We can use this information to see how long a particular person stayed on the site.</p>
<p>Along with this visit data, we&#8217;re going to store some other information about the user being tracked. Thanks to the PHP array $_SERVER, we can get hold of a wide range of useful stats and information about the person.  Here is a sample of some of the information we can retrieve about people arriving at our site.</p>
<p>Referring page - Accessed through the $_SERVER['HTTP_REFERER'] variable. You can use this to see if people have come from a search engine, and this variable will also contain the search terms they used to find you. Very useful for marketing and analysis<br />
IP Address - A handy value to label your visitor records with. This is available through $_SERVER['REMOTE_ADDR']<br />
The current page address - To see which pages our visitors are accessing, we can retrieve the filename for the current page through $_SERVER['SCRIPT_NAME']. We can also grab the query string with $_SERVER['QUERY_STRING']</p>
<p>A selection of other values is available through the $_SERVER array too, but for now, we&#8217;re just going to store and record two values using this array - the current page location, and the IP address of the visitor</p>
<p>Note : IP Addresses can sometimes change, even while a user is browsing a page, so we can&#8217;t rely on these to track them. Instead, we&#8217;re going to rely on the session a user generates while they visit the site. This is unique and unchanging for each individual user, so we can make use of this fact to track them across multiple pages on our site.</p>
<p><a name='MySQL code'></a><br />
<h3>MySQL code</h3>
<p>Run this query in your MySQL management tool to generate the table we&#8217;re going to be using for this application. This is just a simple example of a visitor tracking tool, and doesn&#8217;t contain many fields, but you can add in as many new fields as you like, and it&#8217;s possible to track extra visitor data such as the type of browser they&#8217;re using, their location and more!</p>

<div class="wp_syntax"><div class="code"><pre class="sql"><span style="color: #993333; font-weight: bold;">DROP</span> <span style="color: #993333; font-weight: bold;">TABLE</span> <span style="color: #993333; font-weight: bold;">IF</span> <span style="color: #993333; font-weight: bold;">EXISTS</span> <span style="color: #ff0000;">`visitor_tracking`</span>;
<span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">TABLE</span> <span style="color: #993333; font-weight: bold;">IF</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">EXISTS</span> <span style="color: #ff0000;">`visitor_tracking`</span> <span style="color: #66cc66;">&#40;</span>
  <span style="color: #ff0000;">`entry_id`</span> int<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">11</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span> <span style="color: #993333; font-weight: bold;">AUTO_INCREMENT</span><span style="color: #66cc66;">,</span>
  <span style="color: #ff0000;">`visitor_id`</span> int<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">11</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">DEFAULT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
  <span style="color: #ff0000;">`ip_address`</span> varchar<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">15</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
  <span style="color: #ff0000;">`page_name`</span> text<span style="color: #66cc66;">,</span>
  <span style="color: #ff0000;">`query_string`</span> text<span style="color: #66cc66;">,</span>
  <span style="color: #ff0000;">`timestamp`</span> timestamp <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span> <span style="color: #993333; font-weight: bold;">DEFAULT</span> CURRENT_TIMESTAMP<span style="color: #66cc66;">,</span>
  <span style="color: #993333; font-weight: bold;">PRIMARY</span> <span style="color: #993333; font-weight: bold;">KEY</span>  <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">`entry_id`</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">,</span>
  <span style="color: #993333; font-weight: bold;">KEY</span> <span style="color: #ff0000;">`visitor_id`</span> <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">`visitor_id`</span><span style="color: #66cc66;">,</span><span style="color: #ff0000;">`timestamp`</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#41;</span> ENGINE<span style="color: #66cc66;">=</span>InnoDB  <span style="color: #993333; font-weight: bold;">DEFAULT</span> CHARSET<span style="color: #66cc66;">=</span>latin1;</pre></div></div>

<p><a name='ip_tracker.php'></a><br />
<h3>ip_tracker.php</h3>
<p>First we&#8217;re going to create the file that will do the visitor tracking for us. This file will be include()&#8217;d at the top of each of the pages we wish to track. We&#8217;ll also be tracking by query string, so this will work if your site only uses one file (e.g. index.php) and generates pages based on the value of an id (e.g. index.php?page_id=52)</p>
<p>To start off, we need to set up our database connection and also grab some values from the server about our current visitor, so we can save these to the database later</p>
<pre class="php">//define our &quot;maximum idle period&quot; to be 30 minutes
$mins = 30;
//set the time limit before a session expires
ini_set &#40;&quot;session.gc_maxlifetime&quot;, $mins * 60&#41;;
session_start&#40;&#41;;
$ip_address = $_SERVER&#91;&quot;REMOTE_ADDR&quot;&#93;;
$page_name = $_SERVER&#91;&quot;SCRIPT_NAME&quot;&#93;;
$query_string = $_SERVER&#91;&quot;QUERY_STRING&quot;&#93;;
$current_page = $page_name.&quot;?&quot;.$query_string;
//connect to the database using your database settings
include&#40;&quot;db_connect.php&quot;&#41;;</pre>
<p>Let&#8217;s explain a few things here</p>
<p>$mins = 30 - We need to define a &#8220;timeout&#8221; limit for our visitor tracking tool. If a visitor clicks on a new page within, say, 29 minutes, then that&#8217;ll be counted as part of the same visit. If, however, they go away for an hour or so and come back, we might want to treat that as a new visit. Increase this value if you want to let visitors stay away from the site longer and still count them in the same visit<br />
session_start(); - Start up the session. Very important that you don&#8217;t include any HTML whitespace or other characters before this function call<br />
$ip_address = &#8230; etc. - Grab some useful values from the server including the current visitor&#8217;s IP address, the name of the page we&#8217;re on and anything that&#8217;s in the query string. The current page is generated by joining these last two together<br />
include(&#8221;db_connect.php&#8221;); - Just include whatever code you need in a seperate file to connect to the database. In my case, the code is
</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #666666; font-style: italic;">//change these values to whatever your own database server requires</span>
<span style="color: #000033;">$link</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_connect</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'localhost'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'root'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'pass'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//Connects to the database at &quot;localhost&quot;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #000033;">$link</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">//halt execution if cannot connect</span>
    <span style="color: #990000;">die</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Cannot connect to the database!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #990000;">mysql_select_db</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'test'</span><span style="color: #339933;">,</span> <span style="color: #000033;">$link</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//Assuming you have a database named &quot;test&quot; set up</span></pre></div></div>

<p>Next, we&#8217;re going to consider two different scenarios - first, if the visitor is returning to the site after already having viewed a page. We&#8217;re going to set a value in the $_SESSION array to remember this person, so&#8230;</p>
<pre class="php">if&#40;isset&#40;$_SESSION&#91;&quot;tracking&quot;&#93;&#41;&#41;&#123;
    //update the visitor log in the database, based on the current visitor
    //id held in $_SESSION[&quot;visitor_id&quot;]
    $visitor_id = $_SESSION&#91;&quot;visitor_id&quot;&#93;;
    if&#40;$_SESSION&#91;&quot;current_page&quot;&#93; != $current_page&#41;
    &#123;
        $sql = &quot;INSERT INTO visitor_tracking
            (ip_address, page_name, query_string, visitor_id)
            VALUES ('$ip_address', '$page_name', '$query_string', '$visitor_id')&quot;;
        if&#40;!mysql_query&#40;$sql&#41;&#41;&#123;
            echo &quot;Failed to update visitor log&quot;;
        &#125;
        $_SESSION&#91;&quot;current_page&quot;&#93; = $current_page;
    &#125;
&#125;</pre>
<p>In this first conditional branch, we&#8217;re checking to see if the session variable &#8220;tracking&#8221; has been set. If so, then this means that we&#8217;re already tracking this visitor and so must insert a new entry into the database based on their visitor ID. We&#8217;ll see in just a moment how we generate this visitor ID and also set the appropriate session variables. As long as the session is valid (if the user has been idle for less than 30 minutes), then these values will exist, otherwise they&#8217;ll be deleted and we can count this as a new visit, which is dealt with in the second condition of the IF statement.</p>
<p>line 16 - We check that the current page doesn&#8217;t match the last page the user viewed. We don&#8217;t want to track multiple reloads of the same page<br />
lines 18-20 - The SQL statement to add a new entry to the visitors table. Note how $visitor_id will always be set to the same value, the value held in &#8220;visitor_id&#8221; in the $_SESSION variable. This is so we can track the same visitor across multiple page views. All entries for a specific &#8220;visit&#8221; by a specific user will have the same visitor ID.</p>
<p>Now we&#8217;re going to look at the other conditional branch - when a user visits the page for the first time</p>
<pre class="php">else &#123;
    //set a session variable so we know that this visitor is being tracked
    $_SESSION&#91;&quot;tracking&quot;&#93; = true;
    //insert a new row into the database for this person
    $sql = &quot;INSERT INTO visitor_tracking
        (ip_address, page_name, query_string)
        VALUES ('$ip_address', '$page_name', '$query_string')&quot;;
    if&#40;!mysql_query&#40;$sql&#41;&#41;&#123;
        echo &quot;Failed to add new visitor into tracking log&quot;;
    &#125; else &#123;
        //find the next available visitor_id for the database
        //to assign to this person
        $entry_id = mysql_insert_id&#40;&#41;;
        $lowest_sql = mysql_query&#40;&quot;SELECT MAX(visitor_id) as next FROM visitor_tracking&quot;&#41;;
        $lowest_row = mysql_fetch_array&#40;$lowest_sql&#41;;
        $lowest = $lowest_row&#91;&quot;next&quot;&#93;;
        if&#40;!isset&#40;$lowest&#41;&#41;
            $lowest = 1;
        else
            $lowest++;
        //update the visitor entry with the new visitor id
        mysql_query&#40;&quot;UPDATE visitor_tracking SET visitor_id = '$lowest'
            WHERE entry_id = '$entry_id'&quot;&#41;;
        //place the current visitor_id into the session so we can use it on
        //subsequent visits to track this person
        $_SESSION&#91;&quot;visitor_id&quot;&#93; = $lowest;
        //save the current page to session so we don't track if someone just refreshes the page
        $_SESSION&#91;&quot;current_page&quot;&#93; = $current_page;
    &#125;
&#125;</pre>
<p><a name='ip_report.php'></a><br />
<h3>ip_report.php</h3>
<p>Now we&#8217;ll look at the file where we generate the report data. In the &#8220;head&#8221; of the file (before we add any HTML data) we&#8217;ll add in some PHP preprocessing, code that runs before we need to produce any output</p>
<pre class="php">&lt;?php
include&#40;&quot;db_connect.php&quot;&#41;;
//retrieve the appropriate visitor data
$view = $_GET&#91;&quot;view&quot;&#93;;
//set a default value for $view
if&#40;$view!=&quot;all&quot; &amp;&amp; $view!=&quot;record&quot;&#41;
  $view = &quot;all&quot;;
if&#40;$view == &quot;all&quot;&#41;
&#123;
    //show all recent visitors
    $sql = &quot;SELECT visitor_id, GROUP_CONCAT(DISTINCT ip_address) as ip_address_list,
        COUNT(DISTINCT ip_address) as ip_total, COUNT(visitor_id) as page_count,
        MIN(timestamp) as start_time, MAX(timestamp) as end_time FROM
        visitor_tracking GROUP BY visitor_id&quot;;
    $result = mysql_query&#40;$sql&#41;;
    if&#40;$result==false&#41;&#123;
        $view = &quot;error&quot;;
        $error = &quot;Could not retrieve values&quot;;
    &#125;
&#125; else &#123;
    //show pages for a specific visitor
    $visitor_id = $_GET&#91;'id'&#93;;
    //rung $visitor_id through filter_var to check it's not an invalid
    //value, or a hack attempt
    if&#40;!filter_var&#40;$visitor_id, FILTER_VALIDATE_INT, 0&#41;&#41;&#123;
        $error = &quot;Invalid ID specified&quot;;
        $view = &quot;error&quot;;
    &#125; else &#123;
        $sql = &quot;SELECT timestamp, page_name, query_string, ip_address
            FROM visitor_tracking WHERE visitor_id = '$visitor_id'&quot;;
        $result = mysql_query&#40;$sql&#41;;
    &#125;
&#125;
function display_date&#40;$time&#41;&#123;
    return date&#40;&quot;F j, Y, g:i a&quot;, $time&#41;;
&#125;
&nbsp;
?&gt;</pre>
<p>Some important things to notice here -</p>
<p>lines 11-14 - The SQL code used when we&#8217;re viewing the main page which details all the visitors that have arrived at the site, along with a few bits of information about them. Note the use of the MySQL function GROUP_CONCAT. This is an especially useful function, since it allows us to return a list of all the IP addresses (DISTINCT addresses in this case, since we don&#8217;t need duplicates) as a single string, seperated by commas.</p>
<p>See also how we use COUNT(visitor_id) to get a total page count for that specific visitor. And thanks to the GROUP BY keyword, we can return exactly one record per visitor, which makes processing and displaying the results much simpler<br />
lines 29 &#038; 30 - This is the SQL code we use when we&#8217;re displaying a specific user&#8217;s visit details. This is a simpler query, since we just need a list of all the pages they viewed, and the time they viewed them at.<br />
lines 34-36 - A simple function used to format the date and time later on in the file</p>
<p>We&#8217;ll then generate the body of the page itself, including any HTML output necessary</p>
<pre class="php">&lt;html&gt;
&lt;head&gt;
&lt;title&gt;IP Tracker Report Page&lt;/title&gt;
&lt;style&gt;
html &#123;font-family:tahoma,verdana,arial,sans serif;&#125;
body &#123;font-size:62.5%;&#125;
table tr th&#123;
    font-size:0.8em;
    background-color:#ddb;
    padding:0.2em 0.6em 0.2em 0.6em;
&#125;
table tr td&#123;
    font-size:0.8em;
    background-color:#eec;
    margin:0.3em;
    padding:0.3em;
&#125;
&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;IP Tracker Report&lt;/h1&gt;
&lt;?php if&#40;$view==&quot;all&quot;&#41; &#123;
    //display all of the results grouped by visitor
    if&#40;$row = mysql_fetch_array&#40;$result&#41;&#41;&#123;
    ?&gt;
    &lt;table&gt;
      &lt;tbody&gt;
      &lt;tr&gt;
      &lt;th&gt;Id&lt;/th&gt;
      &lt;th&gt;IP Address&#40;es&#41;&lt;/th&gt;
      &lt;th&gt;Entry Time&lt;/th&gt;
      &lt;th&gt;Exit Time&lt;/th&gt;
      &lt;th&gt;Duration&lt;/th&gt;
      &lt;th&gt;Pages visited&lt;/th&gt;
      &lt;th&gt;Actions&lt;/th&gt;
      &lt;/tr&gt;
    &lt;?php
      do&#123;
        if&#40;$row&#91;&quot;ip_total&quot;&#93; &gt; 1&#41;
            $ip_list = &quot;Multiple addresses&quot;;
        else
            $ip_list = $row&#91;&quot;ip_address_list&quot;&#93;;
        $start_time = strtotime&#40;$row&#91;&quot;start_time&quot;&#93;&#41;;
        $end_time = strtotime&#40;$row&#91;&quot;end_time&quot;&#93;&#41;;
        $start = display_date&#40;$start_time&#41;;
        $end = display_date&#40;$end_time&#41;;
        $duration = $end_time - $start_time;
        if&#40;$duration &gt;= 60&#41; &#123;
            $duration = number_format&#40;$duration/60, 1&#41;.&quot; minutes&quot;;
        &#125;
        else &#123;
            $duration = $duration.&quot; seconds&quot;;
        &#125;
        echo &quot;&lt;tr&gt;&quot;;
        echo &quot;&lt;td&gt;{$row[&quot;visitor_id&quot;]}&lt;/td&gt;&quot;;
        echo &quot;&lt;td&gt;$ip_list&lt;/td&gt;&quot;;
        echo &quot;&lt;td&gt;$start&lt;/td&gt;&quot;;
        echo &quot;&lt;td&gt;$end&lt;/td&gt;&quot;;
        echo &quot;&lt;td&gt;$duration&lt;/td&gt;&quot;;
        echo &quot;&lt;td&gt;{$row[&quot;page_count&quot;]}&lt;/td&gt;&quot;;
        echo &quot;&lt;td&gt;&lt;a href='ip_report.php?view=record&amp;
id={$row[&quot;visitor_id&quot;]}'&gt;view&lt;/a&gt;&lt;/td&gt;&quot;;
        echo &quot;&lt;/tr&gt;&quot;;
      &#125; while &#40;$row = mysql_fetch_array&#40;$result&#41;&#41;;
    ?&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
    &lt;?php &#125; else &#123; ?&gt;
      &lt;h3&gt;No records in the table yet&lt;/h3&gt;
    &lt;?php &#125; ?&gt;
&lt;?php &#125; elseif&#40;$view==&quot;record&quot;&#41;&#123; ?&gt;
  &lt;h3&gt;Showing records for Visitor &lt;?php echo $visitor_id; ?&gt;&lt;/h3&gt;
  &lt;p&gt;&lt;a href=&quot;ip_report.php&quot;&gt;back&lt;/a&gt;&lt;/p&gt;
  &lt;?php
    //show all pages for a single visitor
    if&#40;$row = mysql_fetch_array&#40;$result&#41;&#41;&#123;
    ?&gt;
    &lt;table&gt;
      &lt;tbody&gt;
      &lt;tr&gt;
      &lt;th&gt;Page viewed&lt;/th&gt;
      &lt;th&gt;Query string&lt;/th&gt;
      &lt;th&gt;Time of view&lt;/th&gt;
      &lt;/tr&gt;
    &lt;?php
      do&#123;
        if&#40;$row&#91;&quot;ip_total&quot;&#93; &gt; 1&#41;
            $ip_list = &quot;More than 1&quot;;
        else
            $ip_list = $row&#91;&quot;ip_address_list&quot;&#93;;
        $time = display_date&#40;strtotime&#40;$row&#91;&quot;timestamp&quot;&#93;&#41;&#41;;
        echo &quot;&lt;tr&gt;&quot;;
        echo &quot;&lt;td&gt;{$row[&quot;page_name&quot;]}&lt;/td&gt;&quot;;
        echo &quot;&lt;td&gt;{$row[&quot;query_string&quot;]}&lt;/td&gt;&quot;;
        echo &quot;&lt;td&gt;$time&lt;/td&gt;&quot;;
        echo &quot;&lt;/tr&gt;&quot;;
      &#125; while &#40;$row = mysql_fetch_array&#40;$result&#41;&#41;;
    ?&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
    &lt;?php &#125; else &#123; ?&gt;
      &lt;h3&gt;No records for this visitor&lt;/h3&gt;
    &lt;?php
    &#125;
&#125; elseif&#40;$view==&quot;error&quot;&#41; &#123; ?&gt;
    &lt;h3&gt;There was an error&lt;/h3&gt;
    &lt;?php echo $error;
&#125;
?&gt;
&nbsp;
&lt;/body&gt;
&lt;/html&gt;</pre>
<p>Have a look through the code above. You should be able to see variables being used that were set in the preceding PHP code, to control which page we view (whether it&#8217;s a page of all the available visitors, or a detailed view of one visitor&#8217;s session)</p>
<p><a name='Test Files'></a><br />
<h3>Test Files</h3>
<p>I&#8217;ve also created three test files in the zip package, to let you see how the file ip_tracker.php above should be used. You just need to add an include() call to the file to add it to each page, and then the tracking functionality should be present on all pages where the file is added.</p>
<p>e.g.</p>

<div class="wp_syntax"><div class="code"><pre class="php"> 
Page <span style="color: #cc66cc;">1</span>
This page is now being tracked with IP Tracker<span style="color: #339933;">!</span></pre></div></div>

<p>To test the application, simply visit the test pages on your server and see how the report page at ip_report.php changes as you go. If you&#8217;re running the script on a local machine, you&#8217;ll probably see your IP show up as 127.0.0.1. From anywhere else, if the script is hosted online, you should see something different</p>
<p>To reset the session and see how the output changes when you start a new &#8220;visit&#8221;, open up session_end.php in your browser (included in the zip package), and this will destroy the current session, essentially making you a new visitor when you revisit the test pages.</p>
<p>session_end.php</p>

<div class="wp_syntax"><div class="code"><pre class="php">&nbsp;</pre></div></div>

<p>Download all the files used in this tutorial <a href='http://www.roughguidetophp.com/wp-content/uploads/2008/09/visitor_tracking_php_mysql.zip'>here</a></p>
<p><a name='An important note about performance'></a><br />
<h3>An important note about performance</h3>
<p>User tracking can be a very database intensive process, especially on busy sites, so don&#8217;t use this script on any sites where performance is important. This application serves only as a demonstration of the potential for PHP to perform visitor tracking and many improvements would need to be made before it could be used on data-heavy sites, but feel free to use the code on your own site, and modify or improve it as you feel necessary. Let me know if it&#8217;s been of any use to you!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.roughguidetophp.com/a-simple-ip-address-and-visitor-tracking-tool-with-php-mysql/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Security Issues : Cleaning up User Data in MySQL</title>
		<link>http://www.roughguidetophp.com/cleaning-up-user-data-in-mysql/</link>
		<comments>http://www.roughguidetophp.com/cleaning-up-user-data-in-mysql/#comments</comments>
		<pubDate>Tue, 30 Nov 1999 00:00:00 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[PHP with MySQL]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[
Cleaning up User Input for MySQLDealing With Invalid User DataCase 1 - Invalid HTML TagsSolution 1 : Stripping out HTML tags before inserting via MySQLCase 2 : Using apostrophes and quotation marks in commentsSolution 2 : Escaping quotation characters with mysql_real_escape_string()Case 3 : Preventing SQL injection attacksSolution 3 : Prepare Your Inputs

Cleaning up User Input [...]]]></description>
			<content:encoded><![CDATA[<p><!--pagetitle:How to ensure your User Data remains "safe"--></p>
<p><a href='#Cleaning up User Input for MySQL'>Cleaning up User Input for MySQL</a><a href='#Dealing With Invalid User Data'>Dealing With Invalid User Data</a><a href='#Case 1 - Invalid HTML Tags'>Case 1 - Invalid HTML Tags</a><a href='#Solution 1 : Stripping out HTML tags before inserting via MySQL'>Solution 1 : Stripping out HTML tags before inserting via MySQL</a><a href='#Case 2 : Using apostrophes and quotation marks in comments'>Case 2 : Using apostrophes and quotation marks in comments</a><a href='#Solution 2 : Escaping quotation characters with mysql_real_escape_string()'>Solution 2 : Escaping quotation characters with mysql_real_escape_string()</a><a href='#Case 3 : Preventing SQL injection attacks'>Case 3 : Preventing SQL injection attacks</a><a href='#Solution 3 : Prepare Your Inputs'>Solution 3 : Prepare Your Inputs</a></p>
<p><a name='Cleaning up User Input for MySQL'></a><br />
<h3>Cleaning up User Input for MySQL</h3>
<p><a href='#top'>^Back to top</a></p>
<p>One of the things you&#8217;re going to encounter when using MySQL with PHP sooner, rather than later, is the issues that arise when you start accepting user input in the form of comments or blog posts. Up until now in this tutorial, we&#8217;ve just been using data that we&#8217;ve defined ourselves. We&#8217;ve been able to control what goes into our database tables.</p>
<p>When dealing with the general public though, we can&#8217;t assume anything about the data they submit into our database. In fact, we have to assume the worst, since the worst is what might break our website. Let&#8217;s look at a simple example first of all</p>
<p><a name='Dealing With Invalid User Data'></a><br />
<h3>Dealing With Invalid User Data</h3>
<p><a href='#top'>^Back to top</a></p>
<p>Let&#8217;s assume that we&#8217;re working on creating a brand new website containing useful information about microwave ovens. On this website, we want users to be able to leave comments and discussion points about their experiences with microwave ovens, and general chat with other members. In this tutorial, we&#8217;re not interested in the general workings of such a site, instead we&#8217;re going to look closely at what happens when users submit a wide range of &#8220;faulty&#8221; discussion posts, and what we can do about them</p>
<p>Imagine that this is the general layout of our comment posting area</p>
<pre>&lt;h2&gt;Robin says...&lt;/h2&gt;
Hi everyone, I love microwave ovens
&lt;h2&gt;Bill says...&lt;/h2&gt;
I, too, love microwave ovens</pre>
<p>This is a pretty straightforward layout, with simple headings displaying the name of each poster, and their comment underneath.</p>
<p>The actual process that&#8217;s occuring on our fictitious site is</p>
<p>A user is invited to post a comment using an HTML submission form<br />
This data is sent to our server, where we process a MySQL command along the lines of &#8220;INSERT INTO comments (user_name, user_comment) VALUES (&#8217;Robin&#8217;, &#8216;Hi everyone, I love microwave ovens&#8217;)&#8220;<br />
We then display this data on the website, using commands like &#8220;SELECT user_name, user_comment FROM comments&#8220;</p>
<p>Now, this might all seem perfectly harmless, but in stages 2 and 3 there is a lot of room for error, and with a simple implementation like we have above, many opportunities for people to - willlingly or unwillingly - cause more than a little havoc on our website</p>
<p><a name='Case 1 - Invalid HTML Tags'></a><br />
<h3>Case 1 - Invalid HTML Tags</h3>
<p><a href='#top'>^Back to top</a></p>
<p>In our example above, the user Robin was submitting the comment &#8220;Hi everyone, I love microwave ovens&#8221;. Now, let&#8217;s change that. Consider now that Robin is trying to post the comment &#8220;Hi everyone &lt;h2&gt;HELLO!&lt;/h2&gt;&lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;h1&gt;HEELLLOOO!&lt;/h1&gt;&#8221;. See all those random HTML tags within the comment? This comment will have no problem being accepted into our MySQL query like so</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$user_name</span> <span style="color: #339933;">=</span> <span style="color: #000033;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'user_name'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">//user_name = &quot;Robin&quot;;</span>
<span style="color: #000033;">$user_comment</span> <span style="color: #339933;">=</span> <span style="color: #000033;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'user_comment'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">//user_comment = Hi everyone HELLOHEELLLOOO!</span>
<span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;INSERT INTO comments (user_name, user_comment) VALUES ($user_name, $user_comment&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Our big problem comes in step 3, when we try and display this as HTML. It&#8217;s going to totally mess up our page layout. By allowing our users to submit anything they like, they then have free reign to mess up our page in whatever way they see fit. Fortunately, PHP comes to the rescue and gives us a relatively simple solution to our problem</p>
<p><a name='Solution 1 : Stripping out HTML tags before inserting via MySQL'></a><br />
<h3>Solution 1 : Stripping out HTML tags before inserting via MySQL</h3>
<p><a href='#top'>^Back to top</a></p>
<p>Using a handy PHP function, we can automatically strip whatever tags we don&#8217;t want to allow into our database. The function strip_tags() takes as its arguments, a string and an optional list of allowed tags, and returns a string containing only the characters we want to let in to our database. Consider that we only want to allow the tags &lt;b&gt;, &lt;i&gt; and &lt;u&gt;, for some simple formatting (usually we disallow things like &lt;a&gt; to prevent people from spamming links)</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$bad_text</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;We're not going to allow heading textsbut we will allow bold&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$good_text</span> <span style="color: #339933;">=</span> <span style="color: #990000;">strip_tags</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$bad_text</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">echo</span> <span style="color: #000033;">$good_text</span><span style="color: #339933;">;</span></pre></div></div>

<p>If you run this script, and then look at the source of the output (&#8221;View -&gt; Source&#8221; in most browsers - this is because the tags will be displayed as text, rather than HTML) you will see</p>

<div class="wp_syntax"><div class="code"><pre class="text">We're not going to allow heading textsbut we will allow bold</pre></div></div>

<p>Now, we could run this function on our input data before accepting it into our INSERT query, to ensure that no bad data gets placed inside the SQL code to mess up our formatting</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #666666; font-style: italic;">//user_name = &quot;Robin&quot;;</span>
<span style="color: #000033;">$user_name</span> <span style="color: #339933;">=</span> <span style="color: #990000;">strip_tags</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'user_name'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">//user_comment = Hi everyone HELLOHEELLLOOO!</span>
<span style="color: #000033;">$user_comment</span> <span style="color: #339933;">=</span> <span style="color: #990000;">strip_tags</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'user_comment'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">//user_comment now contains no unwanted HTML tags</span>
<span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;INSERT INTO comments (user_name, user_comment) VALUES ($user_name, $user_comment&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p><a name='Case 2 : Using apostrophes and quotation marks in comments'></a><br />
<h3>Case 2 : Using apostrophes and quotation marks in comments</h3>
<p><a href='#top'>^Back to top</a></p>
<p>You might have noticed that when defining your MySQL query code, you have to pay special attention to the quotation marks used within PHP function calls. For example, in the example</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$address</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;'Maple House', 41 Avenue Drive, Islington&quot;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;INSERT INTO employees (address) VALUES ('$address'));
</span</pre></div></div>

<p>We are trying to insert the address &#8216;Maple House&#8217;, 41 Avenue Drive, Islington, but see how we&#8217;re specifying a house name, and have decided to wrap that in single quotation marks? This will conflict with the syntax of the MySQL function call, since we are already wrapping the whole string in single quotation marks and the INSERT procedure will fail. A solution might be to wrap the address in double quotation marks, but that doesn&#8217;t solve the problem, since the whole string could potentially also be wrapped in double quotes. And what about apostrophes? They always use the single quotation mark.</p>
<p><a name='Solution 2 : Escaping quotation characters with mysql_real_escape_string()'></a><br />
<h3>Solution 2 : Escaping quotation characters with mysql_real_escape_string()</h3>
<p><a href='#top'>^Back to top</a></p>
<p>A good solution to this is to use escaping, so that we can use special characters such as double and single quotation marks within our MySQL queries.  Imagine we wanted to insert the address &#8220;Maple House&#8221;, 36 Baker&#8217;s Street, Islington. This address contains both single and double quotation marks so we need to be careful. Here is an example of using quote escaping to make our data safe for input</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$address</span> <span style="color: #339933;">=</span> <span style="color: #000033;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;address&quot;</span><span style="color: #009900;">&#93;</span>
<span style="color: #666666; font-style: italic;">//$_POST[&quot;address&quot;] is &quot;Maple House&quot;, 36 Baker's Street, Islington;</span>
<span style="color: #000033;">$safe_address</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_real_escape_string</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$address</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;INSERT INTO employees (address) VALUES ('$safe_address')&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">//this is equivalent to INSERT INTO employees (address) VALUES ('&quot;Maple House&quot;, 36 Baker's Street, Islington')</span></pre></div></div>

<p>Here, the PHP function mysql_real_escape_string() will add slashes to all characters that need escaping for entry into a MySQL command, such as single quotes (&#8217;), double quotes (&#8221;) and other slashes ()</p>
<p>Note:  There is a PHP directive, magic_quotes_gpc, which automatically adds slashes to $_GET and $_POST data whenever it is turned on. This is something to consider when dealing with MySQL data input, and you can check the status of this directive by use of get_magic_quotes_gpc()</p>
<p>Note, also:  You must have a MySQL connection already set up, using the mysql_connect() function in order for mysql_real_escape_string() to work. Otherwise it&#8217;ll just return an error.</p>
<p><a name='Case 3 : Preventing SQL injection attacks'></a><br />
<h3>Case 3 : Preventing SQL injection attacks</h3>
<p><a href='#top'>^Back to top</a></p>
<p>One particularly nasty form of attack that can be carried out on your site is the SQL injection attack. In basic terms, this is when a user attempts to send unfiltered data into your database queries to take control of the database and run whatever queries they wish. They could retrieve sensitive data from your database, or even delete every single record on your site.</p>
<p>Here is an example of a simple attempt at an SQL injection attack. Consider this simple MySQL code</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$user</span> <span style="color: #339933;">=</span> <span style="color: #000033;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'username'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$password</span> <span style="color: #339933;">=</span> <span style="color: #000033;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'password'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$result</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;SELECT * FROM users WHERE name = '$user' AND password = '$password'&quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$row</span> <span style="color: #339933;">=</span> fetch_mysql_array<span style="color: #009900;">&#40;</span><span style="color: #000033;">$result</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">//user is authenticated</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This is a simple example of a (very) basic login script, which simply retrieves the username and a password from the $_POST variable (submitted via an HTML form) and checks to see if this user exists in this database along with this password (note that in a real database, the password should be encrypted, but we&#8217;re just using an unencrypted password for our example)</p>
<p>The flaw in our plan lies in the fact that we are using the variables as-they-are, directly inserted into the SQL string. You might not immediately see the flaw in this plan, but consider if we have the following input for the script</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$user</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;Robin&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$password</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;x' OR 'a'='a&quot;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This strange looking example for the variable $password is actually a devious attempt to fool your MySQL code into thinking that a valid attempt has been made to access an area of the site reserved only for authorised users, by making it seem like a valid password has been entered for the user Robin. Let&#8217;s see what happens when this value is entered into our SQL string</p>

<div class="wp_syntax"><div class="code"><pre class="sql"><span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #66cc66;">*</span> <span style="color: #993333; font-weight: bold;">FROM</span> users <span style="color: #993333; font-weight: bold;">WHERE</span> name <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'Robin'</span> <span style="color: #993333; font-weight: bold;">AND</span> password <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'x'</span> <span style="color: #993333; font-weight: bold;">OR</span> <span style="color: #ff0000;">'a'</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">'a'</span></pre></div></div>

<p>Here, the condition &#8220;password = &#8216;x&#8217; OR &#8216;a&#8217;=&#8217;a&#8217;&#8221; will always evaluate to true since we are checking that &#8216;a&#8217; equals &#8216;a&#8217;, which it does. It does not matter if we get the correct value for &#8220;password&#8221;</p>
<p><a name='Solution 3 : Prepare Your Inputs'></a><br />
<h3>Solution 3 : Prepare Your Inputs</h3>
<p><a href='#top'>^Back to top</a></p>
<p>The best defence against SQL injection attacks is vigilance and to maintain a set of personal coding rules whenever you&#8217;re creating MySQL queries. Never allow a situation like the one above to occur, where users have direct access to the values introduced into MySQL code.</p>
<p>Always validate your user defined inputs before accepting them into any SQL strings, and put whatever checks you feel are necessary in place to prevent malicious types from messing up your carefully crafted website.</p>
<p>A simple solution to the above injection example would be to use the mysql_real_escape_string() PHP function to ensure that, whatever input the user provides, it is always checked and treated for such attempts. The following example will prevent any SQL injection attack from taking place</p>

<div class="wp_syntax"><div class="code"><pre class="php"><span style="color: #000033;">$user</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;Robin&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$password</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;x' OR 'a'='a&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000033;">$result</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;SELECT * FROM users WHERE name = '&quot;</span><span style="color: #339933;">.</span><span style="color: #990000;">mysql_real_escape_string</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$user</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;' AND
  password = '&quot;</span><span style="color: #339933;">.</span><span style="color: #990000;">mysql_real_escape_string</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$password</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;'&quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000033;">$row</span> <span style="color: #339933;">=</span> fetch_mysql_array<span style="color: #009900;">&#40;</span><span style="color: #000033;">$result</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">//user is authenticated</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This will attempt to run the MySQL query</p>

<div class="wp_syntax"><div class="code"><pre class="sql"><span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #66cc66;">*</span> <span style="color: #993333; font-weight: bold;">FROM</span> users <span style="color: #993333; font-weight: bold;">WHERE</span> name <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'Robin'</span> <span style="color: #993333; font-weight: bold;">AND</span> password <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'x'</span> <span style="color: #993333; font-weight: bold;">OR</span> <span style="color: #ff0000;">'a'</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">'a'</span></pre></div></div>

<p>Which is perfectly valid, and will try and match the user Robin with the literal password &#8220;x&#8217; OR &#8216;a&#8217;=&#8217;a&#8221; because of the presence of the escaping slashes, and this will fail. Unless that is, of course, the correct password!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.roughguidetophp.com/cleaning-up-user-data-in-mysql/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Column and Data Types in MySQL</title>
		<link>http://www.roughguidetophp.com/column-and-data-types-in-mysql/</link>
		<comments>http://www.roughguidetophp.com/column-and-data-types-in-mysql/#comments</comments>
		<pubDate>Tue, 30 Nov 1999 00:00:00 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[PHP with MySQL]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[

MySQL and Data Storage
MySQL stores data in a tabular format, which makes it easy to visualise the information and print it out in a way that you or I can easily understand. Like all tables, it uses horizontal rows to store individual records, and vertical columns to assign labels to certain attributes about each record. [...]]]></description>
			<content:encoded><![CDATA[<p><!--pagetitle:Data formats in MySQL - VARCHAR, INT, BOOL etc.--></p>
<p><a name='MySQL and Data Storage'></a><br />
<h3>MySQL and Data Storage</h3>
<p>MySQL stores data in a tabular format, which makes it easy to visualise the information and print it out in a way that you or I can easily understand. Like all tables, it uses horizontal rows to store individual records, and vertical columns to assign labels to certain attributes about each record. For example, a table of DVD releases might have a &#8220;release date&#8221;, &#8220;film title&#8221;, &#8220;director&#8221; and so on.</p>
<p>In this tutorial we won&#8217;t be doing anything too technical. Instead, we&#8217;ll be focusing on learning about how MySQL represents the data you give it to store, and the limitations and potential benefits each storage type brings.</p>
<p><a name='Some Sample Data and Column Types'></a><br />
<h3>Some Sample Data and Column Types</h3>
<p>To start off, let&#8217;s create a sample set of data for us to work with in our example, to give you a good idea of the various concepts I&#8217;ll introduce shortly:</p>
<table border="0">
<tr>
<td>Name</td>
<td>Address</td>
<td>Delivery Date</td>
<td>Parcel Received?</td>
<td>Delivery Comments</td>
<td>Previous orders</td>
</tr>
<tr>
<td>Alan Smith</td>
<td>12 Arlington Road</td>
<td>12th Aug 2008</td>
<td>Yes</td>
<td>Customer was very happy with service</td>
<td>5</td>
</tr>
<tr>
<td>Kevin Wilson</td>
<td>55 Kentucky Drive</td>
<td>16th Aug 2008</td>
<td>No</td>
<td>Customer wants detailed receipt</td>
<td>0</td>
</tr>
<tr>
<td>Jim Jeffries</td>
<td>165 Main Street</td>
<td>17th Aug 2008</td>
<td>No</td>
<td>No comments</td>
<td>1</td>
</tr>
</table>
<p>Here you can see a table containing a whole load of information about a fictitious delivery firm. We&#8217;re storing the customer name, their address, the date their delivery is/was due, some comments about their delivery and a number which states the number of previous orders this customer has placed.</p>
<p>Each of these columns can be assigned a specific type based on the format of the data we&#8217;ll be storing in them. Let&#8217;s take a look at each one in turn and see the datatypes we could assign to each column</p>
<p>Name - Our customer names won&#8217;t be too long, and we won&#8217;t be storing anything other than text here, so we can define the &#8220;Name&#8221; column to be of type VARCHAR. Now, VARCHAR has a useful extra property where we can define the length of the data to be stored within the column. In this case, we could define it as VARCHAR(64) to specify that our customer names will be no more than 64 characters in length. VARCHAR fields are limited to only 255 characters in length though, so for lengthier entries, we may need to use something different&#8230;<br />
Address - Our customer addresses could potentially be quite long, and perhaps exceed the 255 character limit imposed by VARCHAR. For our address field, we could use the TEXT datatype. TEXT can hold up to 65,536 characters (64KB) of data, which is plenty for our requirements here, and will allow us to have adequate length addresses, if necessary. Note that we can also have MEDIUMTEXT and LONGTEXT datatypes which can hold 16,777,216 (16MB) and roughly 4 billion (4GB!) characters respectively. You&#8217;ll most likely have no need for these unless you&#8217;re looking to have much longer columns than our address field. We may have use of the MEDIUMTEXT column for our comments field though&#8230;<br />
Delivery Date - Here, we&#8217;re going to make use of MySQL&#8217;s DATE type to store our date. MySQL stores dates in a format suitable for calcuations and operations so that if required, we can do all sorts of useful things with this information. If we wish to retrieve the DATE information, MySQL will provide it to us in the format YYYY-MM-DD (where YYYY = year, MM = month and DD = day). If we also need to know the specific date and time for a record, we can make use of DATETIME which allows us to retrieve data in the format YYYY-MM-DD HH:MM:SS (HH = hours, MM = minutes, SS = seconds). In a later tutorial, we&#8217;ll look at how we can use MySQL&#8217;s date and time functions to manipulate records of this type<br />
Parcel Received? - Here we&#8217;re going to make use of a simple data type called BOOLEAN which means the value can either be TRUE (1) or FALSE (0). Note that here we can also use a datatype TINYINT(1) which is simply saying that this value can be either a 1 or a 0<br />
Delivery Comments - In this field, we might want to make use of the MEDIUMTEXT type, just incase we wish to store a large amount of data relating to a customer&#8217;s order. If you know that you won&#8217;t be storing much data in a column, it&#8217;s wise to use just the TEXT type, or even just VARCHAR so that you can identify which fields will hold the most data.Note that the actual choice of datatype has no real impact on space requirements or efficiency, as MySQL simply uses the amount of storage space necessary to fit in whatever data you place in TEXT, MEDIUMTEXT or LONGTEXT<br />
Previous Orders - Here, we are just storing a numerical value, and for this we could assign a simple INT datatype, representing &#8220;integer&#8221;. Note that you might see the definition INT(11) or similar. The number in the brackets has no real bearing on the performance of the table and it doesn&#8217;t limit the size of number you can store in the INT field, although be aware that INT types have a minimum possible value of -2147483648 to 2147483647 (and if you choose to have the field unsigned i.e. with no negative values that changes to 0 to 4294967295)For our &#8220;previous orders&#8221; column this is quite the overkill though, so a simple TINYINT (-128 to 127 or 0 to 255 unsigned) or SMALLINT (-32768 to 32767 or 0 to 65535 unsigned) will do. It&#8217;s hard to forsee any customer having more than 255 previous orders, but sometimes it&#8217;s good to err on the side of caution, just incase - If this event ever did occur, the database table would become inaccurate</p>
<p>We can also have MEDIUMINT which gives us potential numbers into the billions and BIGINT for when billions just won&#8217;t do, and we need to move into the realm of quintillions (going all the way up to a mind boggling 18,446,744,073,709,551,615) MEDIUMINT is useful for defining unique IDs for tables (MySQL can handle tables with billions of rows each)</p>
<p><a name='What are the limits of MySQL?'></a><br />
<h3>What are the limits of MySQL?</h3>
<p>Some common questions when working with MySQL relate to finding out how much data MySQL might be able to handle. You may be concerned that your website or application will simply use too much data for use with MySQL or that the number of users on your site might cause performance to drop significantly. After all, every call to MySQL uses up some processor time, and the more people using it at once, the more you have to consider the speed of the operation.</p>
<p>Well, have no worries, because these questions have been asked many times before, with more than satisfying answers. As mentioned above, MySQL can easily handle tables with billions of rows and you can have tens of thousands of tables per database. Each of these tables can contain thousands of columns each. The first main hurdle most people encounter when using MySQL databases is the amount of disk space the table takes up, especially when using a remote web host, and that&#8217;s relatively easy to increase.</p>
<p>(It&#8217;s very unlikely you&#8217;ll ever reach the true limits of what MySQL can achieve, not until you&#8217;re put in charge of a web-forum with visitor numbers in the millions and post-counts in the billions!)</p>
<p><a name='The MySQL Representation of this Table'></a><br />
<h3>The MySQL Representation of this Table</h3>
<p>Now that we&#8217;ve covered the main datatypes, I&#8217;m going to show you what this table looks like in MySQL code format. You don&#8217;t need to understand what all this does at the moment, but take a look at the syntax to see how the datatypes I&#8217;ve outlined above fit into the general scheme of things when working inside MySQL.</p>

<div class="wp_syntax"><div class="code"><pre class="sql"><span style="color: #993333; font-weight: bold;">DROP</span> <span style="color: #993333; font-weight: bold;">TABLE</span> <span style="color: #993333; font-weight: bold;">IF</span> <span style="color: #993333; font-weight: bold;">EXISTS</span> <span style="color: #ff0000;">`addresses`</span>;
<span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">TABLE</span> <span style="color: #993333; font-weight: bold;">IF</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">EXISTS</span> <span style="color: #ff0000;">`addresses`</span> <span style="color: #66cc66;">&#40;</span>
  <span style="color: #ff0000;">`name`</span> varchar<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">64</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
  <span style="color: #ff0000;">`address`</span> text <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
  <span style="color: #ff0000;">`delivery_date`</span> date <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
  <span style="color: #ff0000;">`parcel_received`</span> tinyint<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
  <span style="color: #ff0000;">`delivery_comments`</span> mediumtext <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
  <span style="color: #ff0000;">`previous_orders`</span> smallint<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">6</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span>
<span style="color: #66cc66;">&#41;</span> ENGINE<span style="color: #66cc66;">=</span>InnoDB <span style="color: #993333; font-weight: bold;">DEFAULT</span> CHARSET<span style="color: #66cc66;">=</span>latin1;
 
<span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #993333; font-weight: bold;">INTO</span> <span style="color: #ff0000;">`addresses`</span> <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">`name`</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">`address`</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">`delivery_date`</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">`parcel_received`</span>
 <span style="color: #66cc66;">,</span> <span style="color: #ff0000;">`delivery_comments`</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">`previous_orders`</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span>
<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'Alan Smith'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'12 Arlington Road'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'2008-08-12'</span><span style="color: #66cc66;">,</span> <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'Customer was very happy with service'</span><span style="color: #66cc66;">,</span> <span style="color: #cc66cc;">5</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">,</span>
<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'Kevin Wilson'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'55 Kentucky Drive'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'2008-08-16'</span><span style="color: #66cc66;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'Customer wants detailed receipt'</span><span style="color: #66cc66;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">,</span>
<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'Jim Jeffries'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'165 Main Street'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'2008-08-17'</span><span style="color: #66cc66;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'No comments'</span><span style="color: #66cc66;">,</span> <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>The code above will create a table within a MySQL database and then insert all of the values in the table above, named &#8220;addresses&#8221; here. Later on, I&#8217;ll explain all the processes going on in more detail, but for now just familiarise yourself with the idea of tables, rows and columns in MySQL and try to visualise in your mind how all this information can be represented both as data and as text displayed on a screen.</p>
<p>In the next tutorial we&#8217;re going to move on to see how we can perform queries on similar sets of data to ask questions of the database, and get back some useful answers.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.roughguidetophp.com/column-and-data-types-in-mysql/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Creating a Simple Comments and Login System using MySQL and PHP</title>
		<link>http://www.roughguidetophp.com/creating-a-simple-comments-and-login-system-using-mysql-and-php/</link>
		<comments>http://www.roughguidetophp.com/creating-a-simple-comments-and-login-system-using-mysql-and-php/#comments</comments>
		<pubDate>Tue, 30 Nov 1999 00:00:00 +0000</pubDate>
		<dc:creator></dc:creator>
		
		<category><![CDATA[Code Samples]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[
Now that we&#8217;ve got a simple understanding of how to perform SELECT, INSERT and UPDATE MySQL queries (and if not, have a quick review from the last couple of tutorials) we can now work on building ourselves a very simple PHP application to accept user data and save it into our database. This information will [...]]]></description>
			<content:encoded><![CDATA[<p><!--pagetitle:A simple, fully usable application!--></p>
<p>Now that we&#8217;ve got a simple understanding of how to perform SELECT, INSERT and UPDATE MySQL queries (and if not, have a quick review from the last couple of tutorials) we can now work on building ourselves a very simple PHP application to accept user data and save it into our database. This information will then be displayed to anyone visiting the site. We&#8217;ll also take a quick look at how we can generate a script to authenticate administrative users based on a username and password combination and allow those admin users to delete unwanted comments from the database.</p>
<p><a name='A simple comment system using PHP and MySQL'></a><br />
<h3>A simple comment system using PHP and MySQL</h3>
<p>The first thing we&#8217;ll need to do is generate the HTML form that we&#8217;ll use to accept the user data, and include a couple of important settings which will let us access this information later, once the user has submitted the form.</p>
<p>First, here&#8217;s the code you&#8217;ll need to use to generate the HTML form. Save this file somewhere in your PHP directory, with the name mysql_form.php</p>
<pre>&nbsp;
A simple PHP/MySQL form
&lt;h2&gt;Please enter your name and a comment&lt;/h2&gt;
&lt;form action=&quot;form_submit.php&quot; method=&quot;post&quot;&gt;
Name :
&lt;input size=&quot;32&quot; type=&quot;text&quot; name=&quot;username&quot; /&gt;&lt;br&gt;
Comment : &lt;textarea cols=&quot;40&quot; rows=&quot;5&quot; name=&quot;comment&quot;&gt;&lt;/textarea&gt;&lt;br&gt;
&lt;input type=&quot;submit&quot; value=&quot;Send comment&quot; /&gt;
&lt;/form&gt;</pre>
<p>Here, we&#8217;re using the &lt;form&gt; tag to generate a set of text-entry boxes where a user can enter their details, to be sent to the server for processing. We have specified that we wish the data to be sent using the POST delivery method. This simply means that the data will be sent within the request to the server, rather than attached to the query string, as would be the case if we were using the GET method.</p>
<p>Next, we need to create another file which will receive the request from the user, and process the data accordingly. We have specified that this file will be called form_submit.php. Create this file, and within it add the following code</p>

<div class="wp_syntax"><div class="code"><pre class="php">&nbsp;</pre></div></div>

<p>Before we go any further here, I&#8217;ll need to give you two things. Firstly, the contents of the file db_connect.php. What I&#8217;ve done here is simply place the mysql_connect() function within the file db_connect.php to save us having to type out the database connection code twice, as we&#8217;ll be adding that into our initial HTML file, mysql_form.php, in just a moment. Here is the connection file as it is set up on my computer (you may need to change the values to suit your installation of PHP)</p>

<div class="wp_syntax"><div class="code"><pre class="php">&nbsp;</pre></div></div>

<p>Secondly, you&#8217;ll need the structure for the &#8220;comments&#8221; table. This should be created in the same database as is defined in the connection file above</p>

<div class="wp_syntax"><div class="code"><pre class="sql"><span style="color: #993333; font-weight: bold;">DROP</span> <span style="color: #993333; font-weight: bold;">TABLE</span> <span style="color: #993333; font-weight: bold;">IF</span> <span style="color: #993333; font-weight: bold;">EXISTS</span> <span style="color: #ff0000;">`comments`</span>;
<span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">TABLE</span> <span style="color: #993333; font-weight: bold;">IF</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">EXISTS</span> <span style="color: #ff0000;">`comments`</span> <span style="color: #66cc66;">&#40;</span>
  <span style="color: #ff0000;">`id`</span> int<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">11</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span> <span style="color: #993333; font-weight: bold;">AUTO_INCREMENT</span><span style="color: #66cc66;">,</span>
  <span style="color: #ff0000;">`name`</span> varchar<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">64</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
  <span style="color: #ff0000;">`comment`</span> text <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
  <span style="color: #993333; font-weight: bold;">PRIMARY</span> <span style="color: #993333; font-weight: bold;">KEY</span>  <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">`id`</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#41;</span> ENGINE<span style="color: #66cc66;">=</span>InnoDB <span style="color: #993333; font-weight: bold;">DEFAULT</span> CHARSET<span style="color: #66cc66;">=</span>latin1 <span style="color: #993333; font-weight: bold;">AUTO_INCREMENT</span><span style="color: #66cc66;">=</span><span style="color: #cc66cc;">1</span> ;</pre></div></div>

<p>Notice how I&#8217;ve defined three columns, the first being an &#8220;id&#8221; column thay is also declared as a PRIMARY KEY, as well as having the AUTO_INCREMENT attribute set. This is very common practice in MySQL tables, and means we don&#8217;t need to concern ourselves with having comments with duplicate names, for example. These unique IDs also give us an easy way to refer to specific comments by number when administrating them at a future date, or deleting comments we don&#8217;t wish to keep.</p>
<p><a name='Test Run'></a><br />
<h3>Test Run</h3>
<p>Try out the code I&#8217;ve included above. You should be able to see an HTML form and, when you submit that form, you should see a page saying &#8220;The comment was added successfully&#8221;. If not, then something has gone wrong and you should go back and recheck your code. </p>
<p><a name='Checking for invalid data'></a><br />
<h3>Checking for invalid data</h3>
<p>One thing you might notice is if you try and submit the form without adding a name or a comment, then the MySQL query will still complete without a problem, and you&#8217;ll be left with a blank entry in the database. One way to get around this is to modify our code to check for such a situation and, if no data has been entered, prompt the user to go back and try again. The following change to form_submit.php will add this behaviour</p>

<div class="wp_syntax"><div class="code"><pre class="php">&nbsp;</pre></div></div>

<p>If you try again, you&#8217;ll now see that the form will not accept blank data.</p>
<p>There&#8217;s a great deal more to consider when accepting user input into your database, and we&#8217;re going to look at that in further detail in the next section. For now though, we&#8217;ll continue with our example, and provide our visitors with some feedback on the comments posted so far</p>
<p><a name='Modifying the HTML file to display the user comments'></a><br />
<h3>Modifying the HTML file to display the user comments</h3>
<p>With a little bit of modification, we can adjust the file we created earlier, mysql_form.php to display all the comments submitted so far</p>

<div class="wp_syntax"><div class="code"><pre class="php">A simple PHP<span style="color: #339933;">/</span><span style="color: #990000;">MySQL</span> form
Please enter your name and a comment
&nbsp;
Name <span style="color: #339933;">:</span>
&nbsp;
Comment <span style="color: #339933;">:</span> 
&nbsp;
&nbsp;
Here are the comments submitted so far
 </pre></div></div>

<p>In our extended example, we&#8217;re making use of the ORDER BY and LIMIT keywords to show only the 10 latest comments, in order from newest to oldest.</p>
<p>If you try out the code above, you should see the same form on the page mysql_form.php, and underneath, a list of all the comments you&#8217;ve added. If you try adding a new one, and then return to this page, you should see it appear at the top of the list.</p>
<p>On the next page, we&#8217;re going to expand on our example, and see how it&#8217;s possible to add in some administration priveleges to a select group of people using the power of PHP and MySQL</p>
<p>
]]></content:encoded>
			<wfw:commentRss>http://www.roughguidetophp.com/creating-a-simple-comments-and-login-system-using-mysql-and-php/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 10.327 seconds -->
<!-- Cached page served by WP-Cache -->
<!-- Compression = gzip -->