PHP Tutorial

PHP Tutorial #2

Welcome to the second tutorial. Hope you got on alright with the first one. No? Send me an email if there is something you don't understand and I'll try to help. Last time, we created a file from scratch. It might be helpful to create a template file that we can use for creating programs in the future.

First a quick recap. A PHP program resides in a file on the server and can send HTML code to the browser to display information that will be rendered as a web page. If you run the previous program that tests MySQL, if you look at the source of the page then you won't see any of the PHP code only the HTML. On then with the template file. It will look something like this:-

<html>
	<head>
    		<title>PHP test</title>
  	</head>
  	<body>
	<? PHP
		// code goes here
	?> 
  	</body>
</html>

This is very similar to the file we created before. There are the usual HTML tags with a TITLE within the HEAD and the BODY opening to the PHP code. The // double slashes denote a comment (similar to C++ and you can also use a hash # or the /* */ pairs as used in the C programming language but the double slashes will be used in the rest of these tutorials). The rest of the code closes off the page as before. So on to some real coding...

In the tradition of all good (?) tutorials, we start with the familiar Hello World program and here it is:-

<html>
	<head>
    		<title>Hello World!</title>
  	</head>
  	<body>
		<?php
			echo("<H1>Hello World</H1>");
  		?>
	</body>
</html>

This uses the echo statement to write back to the browser. Note the <H1> tags which ensure that the text that is written back to the browser will be rendered in bold text between the BODY tags - remember the browser source won't show the PHP code only what is sent to it which in this case is what is between the quotes of the echo statement and will look something like this:-

Hello World

at the top of the browser window. Now we cold have done this just as easily without PHP using only HTML but this is just the beginning of what can be created. A word of warning before we go any further. You probably want to use PHP to create full database applications or messageboards that pervade the Internet. To get that far will require a lot of work learning th basics so don't think you can just skip ahead and miss out the more basic stuff because you are going to need to know it all before you can start creating mega sites with PHP. Alright, now I've got that off my chest, some more stuff. From now on I won't be showing the HTML code that is in the template but just the PHP but you need to remember that it is still required (yes I know all you experienced PHP'ers are champing at the bit saying that it isn't all required but I'll get to that in future tutorials).

<html>
	<head>
    		<title>Test PHP Vars</title>
  	</head>
  	<body>
		<?php
			$str = PHP_OS;
			echo("OS: $str <BR>");
			$str = PHP_VERSION;
			echo("PHP Version: $str <BR>");
  		?>
	</body>
</html>

The first thing to get to grips with are variables (they are called variables because their contents can vary). These are place holders for information that can then be used from within other commands. This little program will display the version of the Operating System being used and the version number of PHP being used at the server end (I'm showing the HTML one more time but that's it after this). The part we need concern ourselves with is the bit between the PHP tags. $str is a variable. If you are familiar with other programming langugages then you might be tempted to think that $str means it is a string variable - it doesn't. Variables in PHP are not strongly typed. This means that $str can hold anything from strings to numbers. You may be familiar with Visual Basic (or Sinclair SuperBasic on the QL) which has a Variant type that can hold anything - well PHP variables will then be a familiar concept to you. However, even though it can store anything (the $ dollar merely denotes that it is a variable) it is good practice to use a variable name (which can be any length) to give an idea of what it is likely to contain. Here, I expect it to contain a string which in this case is first the Operating System and then the version number. So we use the special PHP command that gives us the OS and assign it to the variable $str. Note that in PHP single = equals signs mean assignment while double == equals means equality (as in the C programming language). This information now stored in $str is then echoed to the browser window and a <BR> break is also included to force a newline (note that in a text file you would use /n for a newline but we'll come to that later). Next we collect the PHP version which will overwrite what is in $str - this doesn't matter as we don't need to use it again but if we did then we would have to use another variable name. This is also sent out to the browser and the page is closed as before. Note that the program will run again if the browser is refreshed (F5) and all the variables will be reset. And thats how we do variables.

This next bitmay need a little more concentration as we are to embark on the tortuous subject of loops. It took me many months to get my head around loops and mulitiple loops still give me a headache. Take a look at this. Here is a typical FOR loop.

<?php
		for ($i=0; $i<5; $i++)
		{
			echo("i = now: $i<BR>");
		}
?>

Remember that it goes between the BODY tags in the template file and needs to be renamed to something else like phpfor.php for example. We'll take it a line at a time.

for ($i=0; $i<5; $i++)

It is split into several parts. The for( is the beginning of the loop command. The variable $i is assigned (or set to) the value of zero. Zero is very important in computer languages and omitting it could lead to the program not behaving as expected as the initial value of $i could be anything - better to be safe. The next bit ($i<5)will allow the loop to operate until the value of $i is just less that 5 (in this case 4). Loops generally start at zero and although initially confusing, it becomes second nature after a while. The third part ($i++) will increment (add to) the value of i$ by one (the ++ means increase by one). Each part is seperated by a semi colon and the closing bracket ends the command. Mistyping any of this will generate an error. Next we have his funny thing:-

{

Anyone familiar with the C programming language will recognize it at once. It tells PHP that a block of code follows. You often find it shown at the end of the preceding line but I prefer it this way. Stricly speaking, the block brackets are not required when only a single line of codes follows but I think it is a good habit to get into and makes the code clearer.

echo("i = now: $i<BR>");

This is the by now familiar echo statement. It will print a short message then the value of $i followed by a break(note the semi-colon ; to show the end of the line). This will have the effect of listing this:-

i = now: 0
i = now: 1
i = now: 2
i = now: 3
i = now: 4

Now what on earth is happening here? The loop starts at zero. It will then follow the curly brace until it reaches the echo line. At that moment, $i is still zero so that is what is printed. The loop will then increment $i (using the $i++ command) which will increase the value of $i to 1 and so it is printed again. This will go on until the value of $i is one less that 5 at which point it will stop. That is a FOR loop.

You may need to take a few minutes to make sure you understand what is going on here. This is a fairly mundane use for a loop but they are very useful and crop up all the time saving the programmer time writing it all out in full and is quite an elegant piece of code.

I think that will do for this tutorial. Next time we'll get into more loops. Until then...

Back

Written by Nick Cheesman. Last updated: 01/04/2004
Please eMail me at:
nickjc@nickjc.co.uk