Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5

PHP - Part 6

How to Program PHP
Tutorial, Part 6

Welcome to part 6 of this series of tutorials! In the last tutorial, we finally introduced some concepts that allowed you to interact with a PHP script on the server. (That was a lot of tutorials to get to something so simple, eh? ) In this tutorial, we will introduce the concept of the loop, which will be an extremely useful concept that we will use in later tutorials. These concepts will become especially important when we start using databases. We're still a good way off from that, but this is nevertheless a very important concept.

Basically, a loop does two very simple things. 1) It executes a block of code over and over again, and 2) it checks some sort of condition each time before it executes. The condition is very important because otherwise, without a condition, a loop would literally execute forever. In PHP, we aren't quite as worried about crashing a server because typically a PHP script is cut off after about 30 seconds of execution time (unless your webhost has an unconventional PHP configuration), but in other programming languages, the implications of "bad loops" could be a lot worse. Tongue

The first "loop" that will be demonstrated is the "while" loop, which looks like this:

$count = 0;

while ($count < 11) 
echo $count. "<br>";
$count = $count + 1;


The above code is actually very simple. A "while" loop simply executes a block of code over and over again, as long as a specific condition is met each time. If you run this script, you will see the script count from 0 to 10 in your browser. What makes it stop at 10?

Notice how the condition of the while statement is "($count < 11)". Basically, the condition is that the $count variable is less than 11. If it is equal to 11 or more, this "while" statement will not execute. If it is less than 11, the while statement will execute, and will continue to execute as long as $count remains less than 11. Now of course it won't increment count by itself, so we'll have to make sure that we do that in our loop to prevent an "endless loop" that runs eternally. Tongue

Notice these lines:

echo $count. "<br>";
$count = $count + 1;

The second line is what actually increments $count by 1. Every time this while loop executes, it will increment $count by 1 because this line is "in" the loop. The line before it simply echoes the value of the $count variable, so you will see it in your browser. It also adds a <br> tag so that each number is on each line, so don't be confused by that part of the statement. What you'll end up seeing in your browser when you run this script will be:


As you can see, the while loop is pretty simple. It is an extremely useful loop in PHP, and it will be important to have a solid understanding of how it works. Of course the while loop isn't the only kind of loop that PHP has to work with. There are several variants, including the do-while loop, which is a variant of the while loop where first the block of code will be executed once, and then it will check against a condition before it runs the loop any additional times. What's different about the do-while loop is that a do-while loop will always execute at least once. A while loop won't even execute at all if the condition is never met, but a do-while loop is guaranteed to run at least once, even if no conditions are ever met.

The do-while loop isn't as common as the while loop, so I won't cover it specifically in this tutorial, but if you would like to learn more about how it works, click here for the official explanation from the online PHP manual.

There are of course several other loops in PHP, but none of them are as essential. One loop that I will cover later on is the for loop. The for loop is like the while loop, but it increments the variable automatically instead of requiring you to make a statement to increment a variable. (this sounds useful, but all it really does is save you one extra line of code. ) There is nothing that can be done with a for loop that cannot be done with a while loop, so this isn't very essential for us to glance over yet. If you would like to gain a better understanding of a for loop now, feel free to look at this page from w3schools.

This has been a fairly short tutorial. In my post below, I will give a more "interactive" example of the while loop, and in future tutorials, we'll continue to dive into more complex concepts. Big Grin - Our next project...
How to Program PHP
Tutorial, Part 6.1

I am now going to make a new "interactive" counter script to add on to this simple tutorial. This will create a very simple form, and once this form is submitted, it will count up to the value that you have entered. Save this to a file named counter.php, and upload it to your server and give it a try!

	// this script creates a counter
	if (isset($_POST['submitted'])) {
		// a form has been submitted, so lets start counting!
		if ((int)$_POST['max'] != null) {
			// checks to see if a number was actually entered. 
			$count = 0;
			while ($count < ($_POST['max'] + 1)) 
				echo $count. "<br>";
				$count = $count + 1;
		else {
		// a number wasn't entered, so we can't count. 
		echo "you didn't enter a number!"; 
	else {
		// no form was submitted, so we will need to generate the form. 
		echo "
		<form action='' method='post'>
		<input type='hidden' name='submitted' value='1'>
		Count to: <input type='text' name='max' value='100'> <br />
		<input type='submit'>


This script makes use of a while loop, and also makes use of a few IF statements to validate the data. As you may also notice, for the first time in my tutorials, I have only made use of one file, despite having both an HTML form and PHP. The HTML form is actually in this PHP file, and this script uses IF statements to allow it to auto-detect whether a form has been submitted.

In the past, I've used separate files for HTML forms to separate them from the PHP for simplicity purposes, but this isn't actually a particularly common practice in many real world applications, largely because it can be inconvenient to create a separate HTML file for every single HTML form on a large application. I felt like this was a good time to go ahead and explain how this is done, and most of my future tutorials will probably do something similar down the road. Anyway, back to explaining...

Notice this line near the top of the script:

Quote:if (isset($_POST['submitted'])) {

This line basically checks to see if a field named "submitted" was set. As you may notice, we're using the isset() function for that purpose. This is probably a function you will see being used in quite a lot of real world scripts.

Also, notice the following line in our script:

Quote:<input type='hidden' name='submitted' value='1'>

Notice that we set its type to be "hidden". Just because it is hidden doesn't mean it can't have a value. It has a default value of 1, so it is always set unless the user decides to tamper with the browser's webmaster tools. Unless someone is trying to cheat our little system, this field in our form will ALWAYS be set to 1 if the form is submitted, even though you can't actually see the field, since it is set to be hidden. Tongue

Anyway, because this field will always be set if the form is submitted, we will use it to serve as a marker for this form that shows the script that it has actually been submitted. When we check with the IF statement to see if it is set, we are actually checking to see if the user submitted a form. If a form was submitted and this marker is set, the script will attempt to process this form. If, however, this marker is not set, the script will know that no form was submitted, so it will generate the form instead.

The script also validates with another IF statement to make sure that a number was actually submitted. If the user leaves the form blank, the form may be submitted and may have the "submitted" marker, but it doesn't have any data to process. Turns out you'll have to do quite a lot of meticulous validation of user input in real world applications, especially when databases are involved. It is one of the most important principles of application security never to trust user input blindly, so we'll be seeing a lot of this in future tutorials. Tongue

Also, notice the following line
<form action='' method='post'>

In the past tutorials, we haven't left the "action" field blank. However, because we are sending the form to the same script that generated the form, we don't have to put anything in this field. Remember, the script can auto-detect whether the form was submitted, so this is a perfectly acceptable practice.

Other than that, this script is pretty simple. It makes use of the while statement, and also makes use of IF statements. I would recommend that you play around with this script on your own to see if you can get a feel for how it works. We'll be using concepts like these quite frequently in future tutorials. Stay tuned! Big Grin - Our next project...
Thanks for the new tutorial! I'll give it a better look when I get my PC powered at home.

Possibly Related Threads…
Thread Author Replies Views Last Post
  PHP - Part 5 Darth-Apple 5 8,756 August 28th, 2013 at 10:10 PM
Last Post: Darth-Apple
  PHP - Part 2 Darth-Apple 2 5,673 August 19th, 2013 at 9:26 PM
Last Post: Darth-Apple
  PHP - Part 1 Darth-Apple 4 8,114 August 19th, 2013 at 7:40 PM
Last Post: Damian B.
  PHP - Part 4 Darth-Apple 0 3,553 August 13th, 2013 at 4:29 PM
Last Post: Darth-Apple

Users browsing this thread: 1 Guest(s)

Makestation Theme/Design Selector

Contact Us | Makestation | Return to Top | Lite (Archive) Mode | RSS Syndication 
Proudly powered by MyBB 1.8, © 2002-2021
Forum design by Makestation Team © 2020 - a modern day time capsule | Makestation Ajax Chat Hosting