PHP Variables
PHP Variables
This is a complete and free PHP programming course for beginners. It's assumed that you
already have some HTML skills. But you don't need to be a guru, by any means. If you need a
refresher on HTML, then click the link for the Web Design course on the left of this page.
Everything you need to get started with this PHP course is set out in section one below. Good
luck!
5. Joining direct text and variable data 10. Floating point numbers
PHP Three - Conditional Logic
1. If Statements 7. Less Than and Greater Than
Page 1 of 251
PHP Four - Working with HTML Forms
1. The HTML Form 7. Check for Submit button clicks
3. The Code for the PHP Times Table 6. The break statement
PHP Six - Arrays in PHP
1. What is an Array? 6. Sorting Array values
Page 2 of 251
PHP Seven - String Manipulation
1. Changing Case 5. Splitting a line of text
2. htmlspecialchars( )
PHP Ten - Working With Files In PHP
1. Working With Files In PHP 5. Writing to files
Page 3 of 251
PHP Eleven - Date and Time Functions
in PHP
1. The date( ) function 3. The getdate( ) Function
2. Read records from a MySQL database 6. Insert, Update, Delete with Prepared
Statements
3. Adding records to a MySQL database
Walkthrough One - PHP User Authentication
1. PHP User Authentication - Introduction 4. The Login script
Page 4 of 251
What is PHP?
PHP is probably the most popular scripting language on the web. It is used to enhance web
pages. With PHP, you can do things like create username and password login pages, check
details from a form, create forums, picture galleries, surveys, and a whole lot more. If you've
come across a web page that ends in PHP, then the author has written some programming code to
liven up the plain, old HTML.
PHP is known as a server-sided language. That's because the PHP doesn't get executed on your
computer, but on the computer you requested the page from. The results are then handed over to
you, and displayed in your browser. Other scripting languages you may have heard of are ASP,
Python and Perl. (You don't need to know any of these to make a start on PHP. In fact, these
tutorials assume that you have no programming experience at all.)
The most popular explanation of just what PHP stands for is "Hypertext Pre-processor". But that
would make it HPP, surely? An alternative explanation is that the initials come from the earliest
version of the program, which was called Personal Home Page Tools. At least you get the letters
"PHP" in the right order!
But PHP is so popular that if you're looking for a career in the web design/web scripting industry
then you just have to know it! In these tutorials, we'll get you up and running. And, hopefully, it
will be a lot easier than you think.
You'll also need to have a server, to test your scripts. Don't worry, though - we've found an easy
way to get a server up and running on your own PC. Move on to the next part to learn more.
Page 5 of 251
What you need to get started with PHP
Before you can write and test your PHP scripts, there's one thing you'll need - a server!
Fortunately, you don't need to go out and buy one. In fact, you won't be spending any extra
money. That's why PHP is so popular! But because PHP is a server-sided scripting language, you
either have to get some web space with a hosting company that supports PHP, or make your
computer pretend that it has a server installed. This is because PHP is not run on your PC - it's
executed on the server. The results are then sent back to the client PC (your computer).
Don't worry if this all sounds a little daunting - we've come across an easier way to get you up
and running. We're going to be using some software called Wampserver. This allows you to test
your PHP scripts on your own computer. (The WAMP of Wampserver stands for Windows,
Apache, MySQL, PHP.) It installs everything you need, if you have a Windows PC. We'll
explain how to get it installed in a moment, and where to get it from. But just a word for non-
windows users.
Apple Users
For Apple use, MAMP is quite good. Like Wampserver, it installs everything you need for this
course. You can download it from here:
https://www.mamp.info/en/
What you're doing here is getting the apache server up and running so that you can run PHP
scripts offline. Pay particular attention to where files are stored, and to the "localhost" address.
Linux Users
There are quite a few sites out there to help Linux users get up and running with the Apache
server and PHP. Unfortunately, there's no easy way like there is for Windows and Mac users.
You best bet is to Google your distro with the following:
Lamp +Ubuntu
Or
Lamp +Debian
There's also quite a few YouTube videos that will help you instal everything you need.
Page 6 of 251
Windows Users
OK, back to Wampserver and Windows. First, you need to download the software. You can get it
from here (this site is nothing to do with ours, by the way):
Download Wampserver
In the next part below, you'll see how to make sure eveything is set and running with
Wampserver.
Hopefully, you have now downloaded and installed Wampserver. This will give you a server on
your own PC (Windows users), somewhere you can test your scripts. If you haven't yet
dowloaded the Wampserver software, you can download it here:
Download Wampserver
If the installation went well, you should have an new icon in the bottom right, where the clock is:
Page 7 of 251
Click the icon to see the menu above (older versions of Wampserver).
In Windows 10, double-click the Wampserver desktop icon after installation. You'll then see a
green square on your taskbar, where the clock is. If you can't see the green square, click the
white arrow to see it:
The image below shows Wampserver 3.0.6 running on a Windows 10 64bit machine:
From here, you can stop the server, exit it, view help files, and see the configuration pages.
Click on localhost, though, and you'll see this page appear: (Localhost just refers to the server
running on your own computer. Another way to refer to your server is by using the IP address
127.0.0.1.)
Page 8 of 251
Click the link under Tools that says phpinfo(). If all went well, you should be looking at the
following page (The one below is a different php version, but don't worry about this - as long as
you see something):
If you saw the above page, then congratulations! Your PHP server is up and running, and you
can make a start scripting PHP pages.
Troubleshooting
If you don't see the info.php page, then you will need to refer to the wampserver forums. The
page you need is here:
Wampserver Forums
Page 9 of 251
Hopefully, your question will already have been asked an answered. (Unfortunately, we can't
answer questions about Wampserver, as it's not our software.)
Whenever you create a new PHP page, you need to save it in your WWW directory. You can see
where this is by clicking its item on the menu:
When you click on www directory, you should see an explorer window appear. This one is from
Windows Vista: (You'll probably have only two files, index and testmysql.)
And here's the folders in Windows 10 (notice that there are lot more files in later versions of
Wampser):
Page 10 of 251
This www folder for Wampserver is usally at this location on your hard drive:
c:/wamp/www/
And this location for newer versions of Wampserver and operating systems:
c:/wamp64/www/
Bear this in mind when you click File > Save As to save your PHP scripts: Save them to your
www directory. (If you on a Mac or Linux, you may need to save PHP files to htdocs folder
instead of a www one.)
Suppose you have created a php script called test1.php. To launch this script, you need to add
the script name after localhost in your browser. So instead of this:
http://localhost/airpollution/index.php
You would type this:
http://localhost/test1.php
You don't type the name of the wamp folder, however. This would be wrong, for example:
Page 11 of 251
c:/wamp/www/test1.php
http://localhost/www/test1.php
Your server knows where the www folder is, so you don't have to type it out: just add the script
name to localhost. Likewise, if you create a folder under www then you'd just type this:
http://localhost/folder_name/script_name.php
OK, we'll assume that everything is now up and running. We'll now start to program in PHP.
Page 12 of 251
PHP Variables
A variable is just a storage area. You put things into your storage areas (variables) so that you
can use and manipulate them in your programmes. Things you'll want to store are numbers and
text.
If you're ok with the idea of variables, then you can move on. If not, think of them like this.
Suppose you want to catalogue your clothing collection. You enlist two people to help you, a
man and a woman. These two people are going to be your storage areas. They are going to hold
things for you, while you tally up what you own. The man and the woman, then, are variables.
You count how many coats you have, and then give these to the man. You count how many
shoes you have, and give these to the woman. Unfortunately, you have a bad memory. The
question is, which one of your people (variables) holds the coats and which one holds the shoes?
To help you remember, you can give your people names! You could call them something like
this:
mr_coats
mrs_shoes
But it's entirely up to you what names you give your people (variables). If you like, they could be
called this:
man_coats
woman_shoes
Or
HimCoats
HerShoes
But because your memory is bad, it's best to give them names that help you remember what it is
they are holding for you. (There are some things your people balk at being called. You can't
begin their names with an underscore (_), or a number. But most other characters are fine.)
OK, so your people (variables) now have name. But it's no good just giving them a name. They
are going to be doing some work for you, so you need to tell them what they will be doing. The
man is going to be holding the coats. But we can specify how many coats he will be holding. If
you have ten coats to give him, then you do the "telling" like this:
mr_coats = 10
Page 13 of 251
So, the variable name comes first, then an equals sign. After the equals sign, you tell your
variable what it will be doing. Holding the number 10, in our case. (The equals sign, by the way,
is not really an equals sign. It's called an assignment operator. But don't worry about it, at this
stage. Just remember that you need the equals sign to store things in your variables.)
However, you're learning PHP, so there's something missing. Two things, actually. First, your
people (variables) need a dollar sign at the beginning (people are like that). So it would be this:
$mr_coats = 10
If you miss the dollar sign out, then your people will refuse to work! But the other thing missing
is something really picky and fussy - a semi-colon. Lines of code in PHP need a semi-colon at
the end:
$mr_coats = 10;
If you get any parse errors when you try to run your code, the first thing to check is if you've
missed the semi-colon off the end. It's very easy to do, and can be frustrating. The next thing to
check is if you've missed out a dollar sign. But back to our people (variables).
So the man is holding ten coats. We can do the same thing with the other person (variable):
$mrs_shoes = 25;
So, $mrs_shoes is holding a value of 25. If we then wanted to add up how many items of clothes
we have so far, we could set up a new variable (Note the dollar sign at the begining of the new
variable):
$total_clothes
We can then add up the coats and the shoes. You add up in PHP like this:
Remember, $mr_coats is holding a value of 10, and $mrs_shoes is holding a value of 25. If you
use a plus sign, PHP thinks you want to add up. So it will work out the total for you. The answer
will then get stored in our new variable, the one we've called $total_clothes. You can also add up
like this:
$total_clothes = 10 + 35;
Again, PHP will see the plus sign and add the two together for you. Of course, you can add up
more than two items:
$total_clothes = 10 + 35 + 7 + 38 + 1250;
Page 14 of 251
But the idea is the same - PHP will see plus signs and then add things up. The answer is then
stored in your variable name, the one to the left of the equals sign.
Again, our variable name starts with a dollar sign ($). We've then given it the name coats1. The
equals sign follows the variable name. After the equals sign, however, we have direct text -
Winter Coats. But notice the double quotation marks around our text. If you don't surround your
direct text with quotation marks, then you'll get errors. You can, however, use single quotes
instead of double quotes. So you can do this:
In the above line, we've started with a single quote and ended with a double quote. This will get
you an error.
$coats2 = "Jackets";
$coats3 = "Summer Coats";
The direct text will then get stored in the variable to the left of the equals sign.
So, to recap, variables are storage areas. You use these storage areas to manipulate things like
text and numbers. You'll be using variables a lot, and on the next few pages you'll see how they
work in practice.
Page 15 of 251
Some Practice with PHP Variables
Testing variables with PHP
First, we'll take a look at how to display what's in your variables. We're going to be viewing our
results on a web page. So see if you can get this script working first, because it's the one we'll be
building on. Using a text editor like Notepad, or your PHP software, type the following. (You
can copy and paste it, if you prefer. But you learn more by typing it out yourself - it doesn't
really sink in unless you're making mistakes!)
<html>
<head>
<title>Variables - Some Practice</title>
</head>
<body>
</body>
</html>
When you've finished typing it all, save the page as variables.php. Then Run the script.
Remember: when you're saving your work, save it to the WWW folder, To run the page, start
your browser up and type this in the address bar:
http://localhost/practice/variables.php
If you've created a folder inside the www folder, then the address to type in your browser would
be something like:
http://localhost/FolderName/variables.php
If you were successful, you should have seen the text "It worked!" displayed in your browser. If
so, Congratulations! You have a working server up and running! (If you're using Wampserver,
you should see an icon in the bottom right of your screen. Click the icon and select Start All
Services from the menu.)
The rest of the script is just plain HTML code. Let's examine the PHP in more detail.
We've put the PHP in the BODY section of an HTML page. Scripts can also, and often do, go
between the HEAD section of an HTML page. You can also write your script without any
Page 16 of 251
HTML. But before a browser can recognise your script, it needs some help. You have to tell it
what kind of script it is. Browsers recognise PHP by looking for this punctuation (called syntax):
<?php ?>
So you need a left angle bracket ( < ) then a question mark ( ? ). After the question mark, type
PHP (in upper or lowercase). After your script has finished, type another question mark. Finally,
you need a right angle bracket ( > ). You can put as much space as you like between the opening
and closing syntax.
To display things on the page, we've used print( ). What you want the browser to print goes
between the round brackets. If you're printing direct text, then you need the quotation marks
(single or double quotes). To print what's inside of a variable, just type the variable name
(including the dollar). Finally, the line of code ends as normal - with a semi-colon (;). Another
way to display things on the page is to use an alternative to print() – echo( ).
Now let's adapt the basic page so that we can set up some variables. We'll try some text first.
Keep the HTML as it is, but change your PHP from this:
To this:
<?php
print("It Worked!");
?>
OK, it's not much of a change! But spreading your code out over more than one line makes it
easier to see what you're doing. Now, it's clear that there's only one line of code - Print. So add
this second line to your code (the one in red):
<?php
print("It Worked!");
?>
We've set up a variable called $test_String. After the equals sign, the text "It Worked!" has been
added. The line is then ended with a semi-colon. Don't run your script yet. Change the Print line
to this:
Page 17 of 251
<?php
$test_String = "It Worked!";
print($test_String);
?>
print($test_String);
<?php
//--------------TESTING VARIABLES------------
print($test_String);
?>
Comments in PHP are for your benefit. They help you remember what the code is supposed to
do. A comment can be added by typing two slashes. This tells PHP to ignore the rest of the line.
After the two slashes, you can type anything you like. Another way to add a comment, is like
this:
Page 18 of 251
<?php
/* --------------TESTING VARIABLES------------
Use this type of comment if you want to spill over to more than one line.
Notice how the comment begin and end.
*/
print($test_String);
?>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa.
Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet
commodo magna eros quis urna.
Whichever method you choose, make sure you add comment to your code: they really do help.
Especially if you have to send your code to someone else!
But you can now run the script above, and test it out.
How did you get on? You should have seen that exactly the same text got printed to the page.
And you might be thinking - what's the big deal? Well, what you just did was to pass some text
to a variable, and then have PHP print the contents of the variable. It's a big step: your coding
career has now begun!
Exercise
Change the text "It Worked!" to anything you like. Then run the script again. Try typing some
numbers in between your double quotes, instead of text.
Page 19 of 251
Exercise
Change the double quotes to single quotes. Did it have any effect? Put a single quote at the
beginning of your text, and a double quote at the end. What happens when you run the code?
Exercise
Delete the dollar sign from the variable name. Then run your code. What error did you get? Put
the dollar sign back, but now delete the semi-colon. Run your code again? What error did you
get, this time? It's well worth remembering these errors - you'll see them a lot when you're
starting out! If you see them in future, you'll be better able to correct your errors.
<html>
<head>
<title>More on Variables</title>
</head>
<body>
<?php
?>
</body>
</html>
We'll now set up a variable and print it to the page. So change your code to this:
<?php
$first_number = 10;
print ($first_number);
?>
All the code does is to print the contents of the variable that we've called $first_number.
Remember: if you're printing direct text then you need quotation marks; if you're printing a
variable name then you leave the quotes out. To see why, run the first script above. Then change
the print line to this:
Page 20 of 251
print ("$first_number");
In other words, add double quotation marks around your variable name. Did it make a
difference? What did you expect would print out? Now change the double quotes to single
quotes. Run your script again. With double quotes, the number 10 still prints; with single quotes,
you get the variable name!
PHP Concatenation
You can join together direct text, and whatever is in your variable. The full stop (period or dot,
to some) is used for this. Suppose you want to print out the following "My variable contains the
value of 10". In PHP, you can do it like this:
<?php
$first_number = 10;
$direct_text = 'My variable contains the value of ';
print($direct_text . “”.””.$first_number);
?>
So now we have two variables. The new variable holds our direct text. When we're printing the
contents of both variables, a full stop is used to separate the two. Try out the above script, and
see what happens. Now delete the dot and then try the code again. Any errors?
<?php
$first_number = 10;
?>
Page 21 of 251
This time, the direct text is not inside a variable, but just included in the Print statement. Again a
full stop is used to separate the direct text from the variable name. What you've just done is
called concatenation. Try the new script and see what happens.
Addition in PHP
OK, let's do some adding up. To add up in PHP, the plus symbol (+) is used. (If you still have
the code open from the previous page, try changing the full stop to a plus symbol. Run the code,
and see what happens.)
To add up the contents of variables, you just separate each variable name with a plus symbol.
Try this new script:
<?php
$first_number = 10;
$second_number = 20;
$sum_total = $first_number + $second_number;
?>
In the above script, we've added a second number, and assigned a value to it:
$second_number = 20;
A third variable is then declared, which we've called $sum_total. To the right of the equals sign,
we've added up the contents of the first variable and the contents of the second variable:
PHP knows what is inside of the variables called $first_number and $second_number, because
we've just told it in the two line above! It sees the plus symbol, then adds the two values
Page 22 of 251
together. It puts the answer to the addition in the variable to the left of the equals sign (=), the
one we've called $sum_total.
This script is a little more complicated than the ones you've been doing. If you're a bit puzzled,
just remember what it is we're doing: adding the contents of one variable to the contents of
another. The important line is this one:
The addition to the right of the equals sign gets calculated first ($first_number +
$second_number). The total of the addition is then stored in the variable to the left of the equals
sign ($sum_total =).
You can, of course, add up more than two numbers. Try this exercise.
Exercise
Add a third variable to your code. Assign a value of 30
to your new variable. Put the sum total of all three
variables into the variable called $sum_total. Use
concatenation to display the results. (In other words,
add up 10, 20, and 30!)
You don't have to use variable names to add up. You can do this:
Or even this:
$number = 10;
But the point is the same - use the plus symbol (+) to add up.
Subtraction in PHP
Page 23 of 251
We're not going to weigh things down by subjecting you to torrents of heavy Math! But you do
need to know how to use the basic operators. First up is subtracting.
<?php
$first_number = 10;
$second_number = 20;
$sum_total = $first_number + $second_number;
print ($sum_total);
?>
Subtraction is more or less the same. Instead of the plus sign (+), simply use the minus sign (-).
Change your $sum_total line to this, and run your code:
The s$sum_total line is more or less the same as the first one. Except we're now using the minus
sign instead (and reversing the two variables). When you run the script you should, of course, get
the answer 10. Again, PHP knows what is inside of the variables called $second_number and
$first_number. It knows this because you assigned values to these variables in the first two
lines. When PHP comes across the minus sign, it does the subtraction for you, and puts the
answer into the variable on the left of the equals sign. We then use a print statement to display
what is inside of the variable.
Just like addition, you can subtract more than one number at a time. Try this:
<?php
$first_number = 10;
$second_number = 20;
$third_number = 100;
$sum_total = $third_number - $second_number -
$first_number;
print ($sum_total);
?>
Page 24 of 251
The answer you should get is 70. You can also mix addition with subtraction. Here's an example:
<?php
$first_number = 10;
$second_number = 20;
$third_number = 100;
print ($sum_total);
?>
Run the code above. What answer did you get? Was it the answer you were expecting? Why do
you think it printed the number it did? If you thought it might have printed a different answer to
the one you got, the reason might be the way we set out the sum. Did we mean 100 - 20, and then
add the 10? Or did we mean add up 10 and 20, then take it away from 100? The first sum would
get 90, but the second sum would get 70.
To clarify what you mean, you can use parentheses in your sums. Here's the two different
versions of the sum. Try them both in your code. But note where the parentheses are:
Version one
$sum_total = ($third_number - $second_number) + $first_number;
Version two
$sum_total = $third_number - ($second_number + $first_number);
It's always a good idea to use parentheses in your sums, just to clarify what you want PHP to
calculate. That way, you won't get a peculiar answer!
Another reason to use parentheses is because of something called operator precedence. In PHP,
some operators (Math symbols) are calculated before others. This means that you'll get answers
that are entirely unexpected! As we'll find out right now in the next part - Multiplication.
Multiplication in PHP
To multiply in PHP (and just about every other programming language), the * symbol is used. If
you see 20 * 10, it means multiply 20 by 10. Here's some code for you to try:
Page 25 of 251
<?php
$first_number = 10;
$second_number = 20;
$sum_total = $second_number * $first_number;
print ($sum_total);
?>
In the above code, we're just multiplying whatever is inside of our two variables. We're then
assigning the answer to the variable on the left of the equals sign. (You can probably guess what
the answer is without running the code!)
Just like addition and subtraction, you can multiply more than two numbers:
<?php
$first_number = 10;
$second_number = 20;
$third_number = 100;
print ($sum_total);
?>
But try this code. See if you can guess what the answer is before trying it out:
<?php
$first_number = 10;
$second_number = 2;
$third_number = 3;
Page 26 of 251
print ($sum_total);
?>
What answer did you expect? If you were expecting to get an answer of 50 then you really need
to know about operator precedence! As was mentioned, some operators (Math symbols) are
calculated before others in PHP. Multiplication and division are thought to be more important
that addition and division. So these will get calculated first. In our sum above, PHP sees the *
symbol, and then multiplies these two numbers first. When it works out the answer, it will move
on to the other symbol, the plus sign. It does this first:
$second_number * $first_number;
$third_number + $second_number
This makes the parentheses more important than ever! Use them to force PHP to work out the
sums your way. Here's the two different version. Try them both:
Version one
$sum_total = $third_number + ($second_number * $first_number);
Version two
$sum_total = ($third_number + $second_number) * $first_number;
Here's we're using parentheses to force two different answers. PHP will work out the sum
between the parentheses first, and then move on to the other operator. In version one, we're using
parentheses to make sure that PHP does the multiplication first. When it gets the answer to the
multiplication, THEN the addition is done. In version two, we're using parentheses to make sure
that PHP does the addition first. When it gets the answer to the addition, THEN the
multiplication is done.
Division in PHP
Page 27 of 251
To divide one number by another, the / symbol is used in PHP. If you see 20 / 10, it means divide
10 into 20. Try it yourself:
<?php
$first_number = 10;
$second_number = 20;
$sum_total = $second_number / $first_number;
print ($sum_total);
?>
Again, you have to be careful of operator precedence. Try this code:
<?php
$first_number = 10;
$second_number = 20;
$third_number = 100;
$sum_total = $third_number - $second_number /
$first_number;
print ($sum_total);
?>
PHP won't work out the sum from left to right! Division is done before subtraction. So this will
get done first:
$second_number / $first_number
Page 28 of 251
And NOT this:
$third_number - $second_number
Using parentheses will clear things up. Here's the two versions for you to try:
Version one
$sum_total = $third_number - ($second_number / $first_number);
Version two
$sum_total = ($third_number - $second_number) / $first_number;
The first version will get you an answer of 98, but the second version gets you an answer of 8!
So remember this: division and multiplication get done BEFORE subtraction and addition. Use
parentheses if you want to force PHP to calculate a different way.
<?php
$first_number = 1.2;
$second_number = 2.5;
$sum_total = $second_number + $first_number;
print ($sum_total);
?>
You add up, subtract, divide and multiply these numbers in exactly the same way as the integers
you've been using. A warning comes with floating point numbers, though: you shouldn't trust
them, if you're after a really, really precise answer!
Some Exercises
To round up this section on number variables, here's a few exercises (In your print statements,
there should be no numbers – just variable names):
Page 29 of 251
Exercise
Write a script to add up the following figures: 198, 134, 76. Use a
print statement to output your answer.
Exercise
Write a script to add up the following two numbers: 15, 45. Then
subtract the answer from 100. Use a print statement to output your
answer.
Exercise
Use variables to calculate the answer to the following sum:
(200 * 15) / 10
PHP If Statements
The reason you are storing this information is so that you can do something with them. If you
have stored a username in a variable, for example, you'll then need to check if this is a valid
username. To help you do the checking, something called Conditional Logic comes in very
handy indeed. In this section, we'll take a look at just what Conditional Logic is. In the next
section, we'll do some practical work.
Conditional Logic
Conditional Logic is all about asking "What happens IF ... ". When you press a button labelled
"Don't Press this Button - Under any circumstance!" you are using Conditional Logic. You are
asking, "Well, what happens IF I do press the button?"
You use Conditional Logic in your daily life all the time:
Page 30 of 251
Conditional Logic uses the "IF" word a lot. For the most part, you use Conditional Logic to test
what is inside of a variable. You can then makes decisions based on what is inside of the
variable. As an example, think about the username again. You might have a variable like this:
$User_Name = "My_Regular_Visitor";
The text "My_Regular_Visitor" will then be stored inside of the variable called $User_Name.
You would use some Conditional Logic to test whether or not the variable $User_Name really
does contain one of your regular visitors. You want to ask:
"IF $User_Name is authentic, then let $User_Name have access to the site."
if ($User_Name == "authentic") {
//Code to let user access the site here;
}
Without any checking, the if statement looks like this:
if ( ) {
You can see it more clearly, here. To test a variable or condition, you start with the word "if".
You then have a pair of round brackets. You also need some more brackets - curly ones. These
are just to the right of the letter "P" on your keyboard (Well, a UK keyboard, anyway). You need
the left curly bracket first { and then the right curly bracket } at the end of your if statement. Get
them the wrong way round, and PHP refuses to work. This will get you an error:
if ($User_Name = = "authentic") }
print ("Access Denied>");
{
And so will this:
Page 31 of 251
if ($User_Name == "authentic") {
The first one has the curly brackets the wrong way round (should be left then right), while the
second one has two left curly brackets.
In between the two round brackets, you type the condition you want to test. In the example
above, we're testing to see whether the variable called $User_Name has a value of "authentic":
($User_Name = = "authentic")
Again, you'll get an error if you don't get your round brackets right! So the syntax for the if
statement is this:
if (Condition_or_Variable_to_test) {
In the next lesson, we'll use if statements to display an image on the page.
We'll use the print statement to "print out" HTML code. As an example, take the following
HTML code to display an image:
Just plain HTML. But you can put that code inside of the print statement:
When you run the code, the image should display. Of course, you'll need an image called
church.jpg, and in a folder called images.
You can find these amongst the files you can download for this course, in the folder called
images. (Go here to get the course files, if you haven't already.)
Copy the images folder to your www (root) directory. Then try the following script:
<?PHP
Page 32 of 251
?>
Save your script to the same folder as the images folder (though NOT inside the images folder).
Now fire up your server, and give it a try. Hopefully, you'll see the church image display, as in
the following graphic:
CHURCH IMAGE
<?PHP
$UserName = “Laziness”;
if ($UserName != “Authentic”) {
print ("Access Denied");
Page 33 of 251
}
?>
<?PHP
$kitten_image = 1;
$church_image = 0;
if ($kitten_image == 1) {
print ("<IMG SRC =images/kitten.jpg>");
}
Type that out, and save it as testImages.php. (Notice how there's no HTML!)
When you run the script, the kitten image should display. Let's look at the code and see what's
happening.
$kitten_image = 1;
$church_image = 0;
A value of 1 has been assigned to the variable called $kitten_image. A value of 0 has been
assigned to the variable called $church_image. Then we have our if statement. Here it is without
the print statement:
Page 34 of 251
if ($kitten_image == 1) {
Notice how there's no semi-colon at the end of the first line - you don't need one. After the word
"if" we have a round bracket. Then comes our variable name: $kitten_image. We want to test
what's inside of this variable. Specifically, we want to test if it has a value of 1. So we need the
double equals sign (==). The double equals sign doesn’t really mean “equals”. It means “has a
value of”.
"If the variable called $kitten_image has a value of 1 then execute some code."
To complete the first line of the if statement we have another round bracket, and a left curly
bracket. Miss any of these out, and you'll probably get the dreaded parse error!
The code we want to execute, though, is the print statement, so that our kitten image will display.
This goes inside of the if statement:
if ($kitten_image == 1) {
But if your if statement only runs to one line, you can just do this:
In other words, keep everything on one line. PHP doesn't care about your spaces, so it's perfectly
acceptable code. Not very readable, but acceptable!
To make use of the church image, here's some new code to try:
<?PHP
$kitten_image = 0;
$church_image = 1;
if ($kitten_image == 1) {
Page 35 of 251
print ("<IMG SRC =images/kitten.jpg>");
}
if ($church_image == 1) {
print ("<IMG SRC =images/church.jpg>");
}
?>
Notice that the $kitten_image variable now has a value of 0 and that $church_image is 1. The
new if statement is just the same as the first. When you run the script, however, the church image
will display. That's because of this line:
if ($kitten_image == 1) {
That says, "If the variable called $kitten_image has a value of 1 ... ". PHP doesn't bother reading
the rest of the if statement, because $kitten_image has a value of 0. It will jump down to our
second if statement and test that:
if ($church_image == 1) {
Since the variable called $church_image does indeed have a value of 1, then the code inside of
the if statement gets executed. That code prints out the HTML for the church image:
Page 36 of 251
if ... else Statements in PHP
Instead of using two if statements, we can use an if ... else
statement. Like this:
<?PHP
$kitten_image = 0;
$church_image = 1;
if ($kitten_image == 1) {
print ("<IMG SRC =images/kitten.jpg>");
}
else {
print ("<IMG SRC =images/church.jpg>");
}
?>
Page 37 of 251
Copy this new script, save your work, and try it out. You should find that the church image
displays in the browser. This time, an if … else statement is being used. Let’s see how it works.
if (condition_to_test) {
}
else {
If you look at it closely, you’ll see that you have a normal If Statement first, followed by an
“else” part after it. Here’s the “else” part:
else {
Again, the left and right curly brackets are used. In between the curly brackets, you type the code
you want to execute. In our code, we set up two variables:
$kitten_image = 0;
$church_image = 1;
The variable called $kitten_image has been assigned a value of 0, and the variable called
$church_image has been assigned a value of 1. The first line of the if statement tests to see what
is inside of the variable called $kitten_image. It’s testing to see whether this variable has a value
of 1.
if ($kitten_image == 1) {
What we’re asking is: “Is it true that $kitten_image holds a value of 1?” The variable
$kitten_image holds a value of 0, so PHP sees this as not true. Because a value of “not true” has
been returned (false, if you like), PHP ignores the line of code for the if statement. Instead, it will
execute the code for the “else” part. It doesn’t need to do any testing – else means “when all
other options have been exhausted, run the code between the else curly brackets.“ For us, that
was this:
else {
So the church image gets displayed. Change your two variables from this:
Page 38 of 251
$kitten_image = 0;
$church_image = 1;
To this:
$kitten_image = 1;
$church_image = 0;
Run your code again and watch what happens. You should see the kitten! But can you work out
why?
You can also add “else if” parts to the If Statements you've been exploring. The syntax is this:
else if (another_condition_to_test) {
<?PHP
$kitten_image = 1;
$church_image = 0;
if ($kitten_image == 1) {
print ("<IMG SRC =images/kitten.jpg>");
}
else if ($church_image == 1) {
print ("<IMG SRC =images/church.jpg>");
Page 39 of 251
}
else {
print ("No value of 1 detected");
}
?>
Here’s we’re just testing to see which of our variables holds a value of 1. But notice the “else if”
lines (and that there’s a space between else and if):
else if ($church_image == 1) {
What you’re saying is “If the previous if statement isn’t true, then try this one.” PHP will then try
to evaluate the new condition. If it’s true (the $church_image variable holds a value of 1), then
the code between the new curly brackets gets executes. If it’s false (the $church_image variable
does NOT holds a value of 1), then the line of code will be ignored, and PHP will move on.
To catch any other eventualities, we have an “else” part at the end. Notice that all parts (if, else
if, and else) are neatly sectioned of with pairs of curly brackets:
if ($kitten_image == 1) {
else if ($church_image == 1) {
else {
You can add as many else if parts as you like, one for each condition that you want to test. But
change your two variables from this:
$kitten_image = 1;
$church_image = 0;
Page 40 of 251
to this:
$kitten_image = 0;
$church_image = 0;
As a nice example of if statements, there is a file called “selectPicture.php” in the files that you
downloaded. It’s in the scripts folder. Copy this to your own www (root) folder. As long as you
have all the images mentioned in the script, they should display. But examine the code for the
script (ignore the HTML form tags for now). What it does is to display an image, based on what
the user selected from a drop down list. If statements are being used to test what is inside of a
single variable.
Don’t worry too much about the rest of the code: concentrate on the if statements. All we’re
doing is testing what is inside of the variable called $picture. We’re then displaying the image
that corresponds to the word held in the variable.
Since you will be using if statements a heck of lot in your coding career, it’s essential that you
have a good grasp of how to use them. To help you along, there’s some more about Conditional
logic in the next section!
if ($variable1 == $variable2) {
Page 41 of 251
if ($what_user_entered != $username) {
print("You're not a valid user of this site!");
}
The above code says, “If what the user entered is NOT the same as the value in the variable
called $username then print something out.
In the next few sections, you'll see some examples of how to use the comparison operators.
You've already used the double equals sign, so we'll start with "Not equal to".
<?PHP
Page 42 of 251
$correct_username = 'logmein';
$what_visitor_typed = 'logMEin';
if ($what_visitor_typed != $correct_username) {
print("You're not a valid user of this site!");
}
?>
Save your work and try it out. You should be able to guess what it does! But the thing to note
here is the new Comparison Operator. Instead of using the double equals sign we’re now using
an exclamation mark and a single equals sign. The rest of the If Statement is exactly the same
format as you used earlier.
The things you’re trying to compare need to be different before a value of true is returned by
PHP. In the second variable ($what_visitor_typed), the letters “ME” are in uppercase; in the
first variable, they are in lowercase. So the two are not the same. Because we used the NOT
equal to operator, the text will get printed. Change your script to this:
$correct_username = 'logmein';
$what_visitor_typed = 'logmein';
if ($what_visitor_typed != $correct_username) {
print("You're not a valid user of this site!");
}
else {
print("Welcome back, friend!");
}
See if you can figure out what has changed. Before you run the script, what will get printed out?
Page 43 of 251
In the next part, we'll have a look at how to use the Less Than ( < ) and Greater Than ( > )
operators.
The Less Than ( < ) and Greater Than ( > ) symbols come in quite handy. They are really useful
in loops (which we'll deal with in another section), and for testing numbers in general.
Suppose you wanted to test if someone has spent more than 100 pounds on your site. If they do,
you want to give them a ten percent discount. The Less Than and Greater Than symbols can be
used. Try this script. Open up your text editor, and type the following. Save your work, and try it
out on your server.
<?PHP
$total_spent = 110;
$discount_total = 100;
?>
By using the Greater Than symbol ( > ), we're saying "If the total spent is greater than the
discount total then execute some code."
The Less Than symbol can be used in the same way. Change your script to this (new lines are in
bold):
<?PHP
$total_spent = 90;
$discount_total = 100;
Page 44 of 251
}
else if($total_spent < $discount_total) {
print("Sorry – No discount!");
?>
In the else if part added above, we're checking to see if the total spent is Less Than ( < )100
pounds. If it is, then a new message is display. Notice that the $total_spent variable has been
reduced to 90.
There is a problem with scripts such as the ones above, however. In the next part, we'll take a
look at the operators for Less Than or Equal To and Greater Than or Equal To.
We can use the same code you created "Less Than or Equal To" and "Greater Than or Equal To".
Change this line in your code:
$total_spent = 90;
to this:
$total_spent = 100;
The reason why nothing printed, and no errors occurred, is because we haven't written any
condition logic to test for equality. We're only checking to see if the two variables are either Less
Than ( < ) each other, or Greater Than ( > ) each other. We need to check if they are the same (as
they now are).
Page 45 of 251
Instead of adding yet another else if part, checking to see if the two totals are equal, we can use
the operators <= (Less Than or Equal To) or >=(Greater Than or Equal To). Here's how. Change
this line in your code:
to this:
The only thing that's changed is the Less Than or Equal to symbol has been used instead of just
the Less Than sign.
Now run your code again. Because we're now saying "If total spent is Less Than or equal to
discount total, then execute the code." So the text gets printed to the screen.
Exercise
Suppose you want to apply the discount if 100 pounds or more has been spent. Change your code
above to display the correct message. Use the >= symbol for this exercise.
Comparison Operators can take a little getting used, but are well worth the effort. If you're
having a hard time with all these Operands, you'll be glad to hear that there's even more of them!
Before we get to them, though, let's take a look at another logic technique you can use – the
Switch Statement.
We tested a single variable that came from a drop-down list. A different picture was displayed on
screen, depending on the value inside of the variable. A long list of if and else … if statements
were used. A better option, if you have only one variable to test, is to use something called a
switch statement. To see how switch statements work, study the following code:
Page 46 of 251
<?php
$picture ='church';
switch ($picture) {
case 'kitten':
print('Kitten Picture');
break;
case 'church':
print('Church Picture');
break;
?>
In the code above, we place the direct text "church" into the variable called $picture. It's this
direct text that we want to check. We want to know what is inside of the variable, so that we can
display the correct picture.
To test a single variable with a Switch Statement, the following syntax is used:
switch ($variable_name) {
case 'What_you_want_to_check_for':
//code here
break;
switch ($variable_name) {
You Start with the word 'Switch' then a pair of round brackets. Inside of the round brackets, you
type the name of the variable you want to check. After the round brackets, you need a left curly
bracket.
case 'What_you_want_to_check_for':
The word 'case' is used before each value you want to check for. In our code, a list of values was
coming from a drop-down list. These value were: church and kitten, among others. These are the
Page 47 of 251
values we need after the word 'case'. After the the text or variable you want to check for, a colon
is needed ( : ).
//code here
After the colon on the 'case' line, you type the code you want to execute. Needless to say, you'll
get an error if you miss out any semi-colons at the end of your lines of code!
break;
You need to tell PHP to "Break out" of the switch statement. If you don't, PHP will simply drop
down to the next case and check that. Use the word 'break' to get out of the Switch statement.
To see the Switch statement in action, there is a file called selectPicture2.php amongst the ones
you downloaded (Go here, if you haven't yet downloaded the files for this course). It’s in the
scripts folder. Try it out, if you like!
If you look at the last few lines of the Switch Statement in this file, you'll see something else you
can add to your own code:
default:
print ("No Image Selected");
The default option is like the else from if … else. It's used when there could be other, unknown,
options. A sort of "catch all" option.
In the next part, we'll take a look at something called Logial Operators.
As well as the PHP comparison operators you saw earlier, there's also something called Logical
Operators. You typically use these when you want to test more than one condition at a time. For
example, you could check to see whether the username and password are correct from the same
If Statement. Here's the table of these Operands.
Page 48 of 251
The new Operands are rather strange, if you're meeting them for the first time. A couple of them
even do the same thing! They are very useful, though, so here's a closer look.
<?PHP
$username ='user';
$password ='password';
print("Welcome back!");
}
else {
?>
The if statement is set up the same, but notice that now two conditions are being tested:
Page 49 of 251
$username =='user' && $password =='password
This says, "If username is correct AND the password is ok, too, then let them in". Both
conditions need to go between the round brackets of your if statement.
The | | Operator
The two straight lines mean OR. Use this symbol when you only need one of your conditions to
be true. For example, suppose you want to grant a discount to people if they have spent more
than 100 pounds OR they have a special key. Else they don't get any discount. You'd then code
like this:
$total_spent =100;
$special_key ='SK12345';
print("Discount Granted!");
}
else {
This time we're testing two conditions and only need ONE of them to be true. If either one of
them is true, then the code gets executed. If they are both false, then PHP will move on.
AND and OR
These are the same as the first two! AND is the same as && and OR is the same as ||. There is a
subtle difference, but as a beginner, you can simply replace this:
With this
And this:
With this:
Page 50 of 251
It's up to you which you use. AND is a lot easier to read than &&. OR is a lot easier to read than
||.
XOR
You probably won't need this one too much. But it's used when you want to test if one value of
two is true but NOT both. If both values are the same, then PHP sees the expression as false. If
they are both different, then the value is true. Suppose you had to pick a winner between two
contestants. Only one of them can win. It's an XOR situation!
$contestant_one = true;
$contestant_two = true;
}
else {
See if you can guess which of the two will print out, before running the script.
The ! Operator
This is known as the NOT operator. You use it test whether something is NOT something else.
You can also use it to reverse the value of a true or false value. For example, you want to reset a
variable to true, if it's been set to false, and vice versa. Here's some code to try:
$test_value = false;
if ($test_value == false) {
print(!$test_value);
The code above will print out the number 1! (You'll see why when we tackle Boolean values
below.) What we're saying here is, "If $test_value is false then set it to what it's NOT." What it's
NOT is true, so it will now get this value. A bit confused? It's a tricky one, but it can come in
handy!
Page 51 of 251
PHP Booleans
A Boolean value is one that is in either of two states. They are known as True or False values, in
programming. True is usually given a value of 1, and False is given a value of zero. You set them
up just like other variables:
$true_value = 1;
$false_value = 0;
You can replace the 1 and 0 with the words "true" and "false" (without the quotes). But a note of
caution, if you do. Try this script out, and see what happens:
<?php
$true_value = true;
$false_value = false;
print ("true_value = " . $true_value);
print (" false_value = " . $false_value);
?>
What you should find is that the true_value will print "1", but the false_value won't print
anything! Now replace true with 1 and false with 0, in the script above, and see what prints out.
Boolean values are very common in programming, and you often see this type of coding:
$true_value = true;
if ($true_value) {
Page 52 of 251
print("that's true");
This is a shorthand way of saying "if $true_value holds a Boolean value of 1 then the statement
is true". This is the same as:
if ($true_value == 1) {
print("that's true");
The NOT operand is also used a lot with this kind of if statement:
$true_value = true;
if (!$true_value) {
print("that's true");
}
else {
You'll probably meet Boolean values a lot, during your programming life. It's worth getting the
hang of them!
In recent editions of PHP, two new operators have been introduced: the triple equals sign ( = = =)
and an exclamation, double equals ( != =). These are used to test if one value has the same as
another AND are of the same type. An example would be:
$number = 3;
$text = 'three';
print("Same");
Page 53 of 251
}
else {
So this asks, "Do the variables match exactly?" Since one is text and the other is a number, the
answer is "no", or false. We won't be using these operators much, if at all!
Here's a list of the operators you've met so far, and the order of precedence. This can make a
difference, as we saw during the mathematical operators. Don't worry about these too much,
unless you're convinced that your math or logical is correct. In which case, you might have to
consult the following:
The only operators you haven't yet met on the list above are the = = = and != = operators.
In recent editions of PHP, two new operators have been introduced: the triple equals sign ( = = =)
and an exclamation, double equals ( != =). These are used to test if one value has the same as
another AND are of the same type. An example would be:
$number = 3;
$text = 'three';
print("Same");
}
else {
Page 54 of 251
So this asks, "Do the variables match exactly?" Since one is text and the other is a number, the
answer is "no", or false. We won't be using these operators much, if at all!
Ok, if all of that has given you a headache, let's move on to some practical work. In the next
section, we'll take a look at HTML forms, and how to get data from them. This is so that we can
do other things besides printing to the screen.
If you know a little HTML, then you know that the FORM tags can be used to interact with your
users. Things that can be added to a form are the likes of text boxes, radio buttons, check boxes,
drop down lists, text areas, and submit buttons. A basic HTML form with a textbox and a Submit
button looks like this:
<html>
<head>
<title>A BASIC HTML FORM</title>
</head>
<body>
Page 55 of 251
</FORM>
</body>
</html>
We won't explain what all the HTML elements do, as this is a book on PHP. Some familiarity
with the above is assumed. But we'll discuss the METHOD, ACTION and SUBMIT attributes
in the form above, because they are important.
The above form can be found in the files you download. It's in the scripts folder, and is called
basicForm.php. Use it as a template, if you like.
So, create the form above. Save your work as basicForm.php. (This name will be VERY
important!) Start your server, and make sure the form loads ok in your browser. You should be
able to see a text box and a Submit button. Here's what it should look like:
If a user comes to your site and has to login, for example, then you'll need to get the details from
textboxes. Once you get the text that the user entered, you then test it against a list of your users
(this list is usually stored on a database, which we'll see how to code for in a later section). First,
you need to know about the HTML attributes METHOD, ACTION and SUBMIT. We'll explore
these in the next few sections.
If you look at the first line of our form from you'll notice a METHOD attribute:
The Method attribute is used to tell the browser how the form information should be sent. The
two most popular methods you can use are GET and POST. But our METHOD is blank. So
change it to this:
Page 56 of 251
To see what effect using GET has, save your work again and then click the Submit button on
your form. You should see this:
The thing to notice here is the address bar. After basicForm.php, we have the following:
?Submit1=Login
This is a consequence of using the GET method. The data from the form ends up in the address
bar. You'll see a question mark, followed by form data. In the image above, Submit1 was the
NAME of the button, and Login was the VALUE of the button (the text on the button). This is
what is being returned by the GET method. You use the GET method when the data you want
returned is not crucial information that needs protecting.
You saw what happened in the browser's address bar when you used the GET method for Form
data. The alternative to GET is to use POST. Change the first line of your FORM to this:
Page 57 of 251
The ?Submit1=Login part from the previous section is now gone! That is because we used POST
as the method. Using POST means that the form data won't get appended to the address in the
address bar for all to see. We'll use both POST and GET throughout the book. But it depends on
the project: if the data is not sensitive then use GET, otherwise use POST.
Another important attribute of the Form tag is Action. Without Action, your forms won't go
anywhere!
The Action attribute is crucial. It means, "Where do you want the form sent?". If you miss it out,
your form won't get sent anywhere. You can send the form data to another PHP script, the same
PHP script, an email address, a CGI script, or any other form of script.
In PHP, a popular technique is to send the script to the same page that the form is on – send it to
itself, in other words. We'll use that technique first, but you'll see both techniques in action.
So you need to change the form you have been creating in the previous sections, the one that
should be called basicForm.php. Locate the following, and amend the ACTION line to this:
Page 58 of 251
<Form Name ="form1" Method ="POST" ACTION = "basicForm.php">
So we're going to be sending the form data to exactly the same page as the one we have loaded –
to itself. We'll put some PHP on the page to handle the form data. But for now, save your work
again and then click your submit button. You won't see anything different, but you shouldn't see
any error message either!
Once your script has an Action attribute set, you can then Submit it.
The HTML Submit button is used to submit form data to the script mentioned in the ACTION
attribute. Here's ours:
So the page mentioned in the ACTION attribute is basicForm.php. To Submit this script, you just
need a HTML Submit button:
You don't need to do anything special with a Submit button – all the submitting is done behind
your back. As long as SUBMIT has an ACTION set, then your data will get sent somewhere. But
the NAME attribute of the Submit buttons comes in very handy. You can use this Name to test if
the form was really submitted, or if the user just clicked the refresh button. This is important
when the PHP script is on the same page as the HTML form. Our Submit button is called
"Submit1", but you can call it almost anything you like.
Now that you know about METHOD, ACTION, and SUBMIT, we can move on to processing
the data that the user entered. First, how to get values from our text box.
Page 59 of 251
PHP and Text Boxes on HTML Forms
If you've been following along from the previous sections then your basicForm.php now has a
METHOD and ACTION set. We're going to use these to process text that a user has entered into
a text box. The METHOD attribute tells you how form data is being sent, and the ACTION
attribute tells you where it is being sent.
To get at the text that a user entered into a text box, the text box needs a NAME attribute. You
then tell PHP the NAME of the textbox you want to work with. Our text box hasn't got a NAME
yet, so change your HTML to this:
The NAME of our textbox is username. It's this name that we will be using in a PHP script.
To return data from a HTML form element, you use the following strange syntax:
$_POST['formElement_name'];
$Your_Variable = $_POST['formElement_name'];
Before we explain all the syntax, add the following PHP script to the HTML code you have so
far. Make sure to add it the HEAD section of your HTML (the part to add is in bold):
<html>
<head>
<title>A BASIC HTML FORM</title>
<?PHP
Page 60 of 251
$username = $_POST['username'];
print ($username);
?>
</head>
Save your work again, and click the submit button to run your script. (Don't worry if you see an
error message about "Undefined index". Click the button anyway.) You should see this appear
above your text box:
Delete the text "username" from the textbox, and click the button again. Your new text should
appear above the textbox. The text box itself, however, will still have "username" in it. This is
because the text box is getting reset when the data is returned to the browser. The Value attribute
of the text box is what is being displayed.
The $_POST[ ] is an inbuilt function you can use to get POST data from a form. If you had
METHOD = "GET" on your form, then you'd used this instead:
$username = $_GET['username'];
So you begin with a dollar sign ($) and an underscore character ( _ ). Next comes the METHOD
you want to use, POST or GET. You need to type a pair of square brackets next. In between the
square brackets, you type the NAME of your HTML form element – username, in our case.
$_POST['username'];
Whatever the VALUE was for your HTML element is what gets returned. You can then assign
this to a variable:
$username = $_POST['username'];
So PHP will look for a HTML form element with the NAME username. It then looks at the
VALUE attribute for this form element. It returns this value for you to use and manipulate.
Page 61 of 251
At the moment, all we're doing is returning what the user entered and printing it to the page. But
we can use a bit of Conditional Logic to test what is inside of the variable. As an example,
change your PHP to this:
$username = $_POST['username'];
if ($username == "letmein") {
}
else {
We're now checking to see if the user entered the text "letmein". If so, the username is correct; if
not, print another message.
Try it out an see what happens. When you first load the page, before you even click the button,
you might see the text "You're not a member of this site" displayed above the textbox. That's
because we haven't checked to see if the Submit button on the form was clicked.
Page 62 of 251
You saw how to get text from a textbox when a Submit button on a form was clicked. However,
when you first load the page the text still displays.
The reason why the text displays when the page is first loaded is because the script executes
whether the button is clicked or not. This is the problem you face when a PHP script is on the
same page as the HTML, and is being submitted to itself in the ACTION attribute.
To get round this, you can do a simple check using another IF Statement. What you do is to
check if the Submit button was clicked. If it was, then run your code. To check if a submit button
was clicked, use this:
if ( isset( $_POST['Submit1'] ) ) { }
Now that looks a bit messy! But it actually consists of three parts:
if ( ) { }
isset( )
$_POST['Submit1']
You know about the if statement. But in between the round brackets, we have isset( ). This is an
inbuilt function that checks if a variable has been set or not. In between the round brackets, you
type what you want isset( ) to check. For us, this is $_POST['Submit']. If the user just refreshed
the page, then no value will be set for the Submit button. If the user did click the Submit button,
then PHP will automatically return a value. Change you script from the previous page to the
following and try it out:
if (isset($_POST['Submit1'])) {
$username = $_POST['username'];
if ($username == "letmein") {
}
else {
Make a note of where all those messy round, square and curly brackets are. Miss one out and
you'll get an error!
Page 63 of 251
In the next part, you'll see how to submit your form data to a PHP script on a different page.
You don't have to submit your form data to the same PHP page, as we've been doing. You can
send it to an entirely different PHP page. To see how it works, try this:
Create the following page, and call it basicForm2.php. This is your HTML. Notice the
ACTION attribute.
<html>
<head>
<title>A BASIC HTML FORM</title>
</head>
<body>
</FORM>
</body>
</html>
<?PHP
$username = $_POST['username'];
if ($username == "letmein") {
}
else {
Page 64 of 251
print ("You're not a member of this site");
?>
In the PHP script above, notice how there's no HTML tags. And we've left out the code that
checks if the Submit button was clicked. That's because there's no PHP left in the first page. The
code only gets executed IF the Submit is clicked.
Posting form data to a different PHP script is a way to keep the HTML and PHP separate. But
there is a problem with it, which you will have noticed: the script gets executed on a new page.
That means your form will disappear!
We'll keep the PHP and HTML together. But there will be times when you do want to send form
data to a different PHP page, as we'll see in later sections.
Page 65 of 251
You've been following along and building up a HTML form. You've learned how to get the text
from a text box on a form, but there is a problem.
When the basicForm.php form is submitted, the details that the user entered get erased. You're
left with the VALUE that was set in the HTML. For us, username kept appearing in the text box
when the button was clicked. You can keep the data the user entered quite easily.
Your script should now look like the one in the link below. If not copy and paste this script, and
test it out on your server. (Save the script as basicForm.php.)
<html>
<head>
<title>A BASIC HTML FORM</title>
<?PHP
if (isset($_POST['Submit1'])) {
$username = $_POST['username'];
if ($username = = "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
}
?>
</head>
<body>
<Form name ="form1" Method ="POST" Action ="basicForm.php">
<Input Type = "text" Value ="username" Name ="username">
<Input Type = "Submit" Name = "Submit1" Value = "Login">
</FORM>
</body>
</html>
If you look at the VALUE attribute of the text box in the HTML from the above script, you'll see
that it's set to "username". Because the form gets posted back to itself, this value will keep re-
appearing in the textbox when the page is submitted. Worse, if you've left the Value attributes
empty then everything the user entered will disappear. This can be very annoying, if you're
asking the user to try again. Better is to POST back the values that the user entered.
Page 66 of 251
To post the details back to the form, and thus keep the data the user has already typed out, you
can use this:
In other words, the VALUE attribute is now a PHP line of code. The line of code is just this:
<?PHP
print $username ;
?>
You also need to amend your PHP code in the HEAD section to include an else statement:
if (isset($_POST['Submit1'])) {
$username = $_POST['username'];
if ($username == "letmein") {
}
else {
}
else {
$username ="";
In the else statement at the end, we're just setting the value of the variable called $username for
when the button is NOT clicked, i.e. when the page is refreshed.
However, there are some security issues associated with textboxes (and other form elements). So
we'll see a more secure way to handle these in a later section.
But our new line of HTML for our textbox reads like this:
Page 67 of 251
<INPUT TYPE = 'TEXT' Name ='username' VALUE="<?PHP print $username ; ?>">
In other words, we're now printing out the VALUE attribute with PHP code.
Now that you know a few things about getting values from HTML forms, here's a few exercise
Exercise
Add two text boxes and a Submit button to a HTML form. Invite the user to enter a first name
and surname. When the button is clicked, print out the person's full name. Don't worry about
what is in the text boxes after the button is clicked.
Exercise
Using the same form as the previous exercise, display the first name and surname in the
textboxes, instead of printing them out.
Exercise
Suppose your web site has only 5 users. Create a HTML form to check if a visitor is one of the 5
users. Display a suitable message.
Page 68 of 251
A Radio Button is a way to restrict users to having only one choice. Examples are :
Male/Female, Yes/No, or answers to surveys and quizzes.
Here's a simple from with just two radio buttons and a Submit button:
Make sure you save your work as radioButton.php, as that's where we're posting the Form – to
itself.
To get the value of a radio button with PHP code, again you access the NAME attribute of the
HTML form elements. In the HTML above, the NAME of the Radio buttons is the same –
"gender". The first Radio Button has a value of "male" and the second Radio Button has a value
of female. When you're writing your PHP code, it's these values that are returned. Here's some
PHP code. Add it to the HEAD section of your HTML:
<?PHP
$selected_radio = $_POST['gender'];
print $selected_radio;
?>
This is more or less the same code as we used for the text box! The only thing that's changed
(apart from the variable name) is the NAME of the HTML form element we want to access –
"gender". The last line just prints the value to the page. Again, though, we can add code to detect
if the user clicked the Submit button:
if (isset($_POST['Submit1'])) {
$selected_radio = $_POST['gender'];
print $selected_radio;
Again, this is the same code you saw earlier – just access the form element called 'Submit1' and
see if it is set. The code only executes if it is.
Page 69 of 251
Try out the code. Select a radio button and click Submit button. The choice you made is printed
to the page - either "male" or "female". What you will notice, however, when you try out the
code is that the dot disappears from your selected radio button after the Submit is clicked. Again,
PHP is not retaining the value you selected. The solution for radio Buttons, though, is a little
more complex than for text boxes
Radio buttons have another attribute - checked or unchecked. You need to set which button was
selected by the user, so you have to write PHP code inside the HTML with these values -
checked or unchecked. Here's one way to do it:
<?PHP
$male_status = 'unchecked';
$female_status = 'unchecked';
if (isset($_POST['Submit1'])) {
$selected_radio = $_POST['gender'];
if ($selected_radio = = 'male') {
$male_status = 'checked';
}
else if ($selected_radio = = 'female') {
$female_status = 'checked';
?>
Page 70 of 251
<FORM name ="form1" method ="post" action ="radioButton.php">
<P>
<Input type = "Submit" Name = "Submit1" VALUE = "Select a Radio Button">
</FORM>
Did we say a little more complex? OK, it's much more complex than any code you've written so
far! Have a look at the PHP code inside the HTML first:
This is just a print statement. What is printed out is the value inside of the variable. What is
inside of the variable will be either the word "checked" or the word "unchecked". Which it is
depends on the logic from our long PHP at the top of the page. Let's break that down.
$male_status = 'unchecked';
$female_status = 'unchecked';
These both get set to unchecked. That's just in case the page is refreshed, rather than the Submit
button being clicked.
if (isset($_POST['Submit1'])) {
Exactly the same as before. As is the next line that puts which radio button was selected into the
variable:
$selected_radio = $_POST['gender'];
We then need some conditional logic. We need to set a variable to "checked", so we have an if,
else … if construction:
Page 71 of 251
if ($selected_radio == 'male') {
}
else if ($selected_radio == 'female') {
All we're doing is testing what is inside of the variable called $selected_radio. If it's 'male' do one
thing; if it's 'female', do another. But look at what we're doing:
if ($selected_radio == 'male') {
$male_status = 'checked';
}
else if ($selected_radio = = 'female') {
$female_status = 'checked';
If the 'male' button was clicked then set the $male_status variable to a value of 'checked'. If the
'female' option button was clicked then set the $female_status variable to a value of 'checked'.
So the code works because of the values inside of two variables: $male_status and
$female_status.
Yes, the code is very messy – but radio Buttons can be a quite tricky, when you want to retain
the value of the selected item.
Page 72 of 251
Like Radio buttons, checkboxes are used to give visitors a choice of options. Whereas Radio
Buttons restrict users to only one choice, you can select more than one option with Checkboxes.
Here's a page that asks users to choose which course books they want to order:
As you can see, five items can be selected. Only three are chosen at the moment. When the
button is clicked you, as the programmer, want to do at least two things: record which
checkboxes were ticked, and have PHP "remember" which items were chosen, just in case of
errors.
You don't want the ticks disappearing from the checkboxes, if the user has failed to enter some
other details incorrectly. We saw with Radio Buttons that this can involve some tricky coding.
The same is true for checkboxes. Let's have a look at one solution to the problem.
<html>
<head>
<title>Checkboxes</title>
<?PHP
$ch1 = 'unchecked';
$ch2 = 'unchecked';
$ch3 = 'unchecked';
$ch4 = 'unchecked';
$ch5 = 'unchecked';
if (isset($_POST['Submit1'])) {
if (isset($_POST['ch1'])) {
$ch1 = $_POST['ch1'];
if ($ch1 = = 'net') {
$ch1 = 'checked';
}
}
if (isset($_POST['ch2'])) {
$ch2 = $_POST['ch2'];
if ($ch2 = = 'word') {
$ch2 = 'checked';
Page 73 of 251
}
}
if (isset($_POST['ch3'])) {
$ch3 = $_POST['ch3'];
if ($ch3 == 'excel') {
$ch3 = 'checked';
}
}
if (isset($_POST['ch4'])) {
$ch4 = $_POST['ch4'];
if ($ch4 = = 'web') {
$ch4 = 'checked';
}
}
if (isset($_POST['ch5'])) {
$ch5 = $_POST['ch5'];
if ($ch5 = = 'php') {
$ch5 = 'checked';
}
}
}
?>
</head>
<body>
Page 74 of 251
<?PHP print $ch3; ?>
>Microsoft Excel
<P>
<Input type = 'Checkbox' Name ='ch4' value="web"
<?PHP print $ch4; ?>
>Web Design
<P>
<Input type = 'Checkbox' Name ='ch5' value="php"
<?PHP print $ch5; ?>
>PHP for the Beginner
<P>
</body>
</html>
Note one thing about the HTML checkbox elements: they all have different NAME values (ch1,
ch2 ch3, etc). When we coded for the Radio Buttons, we gave the buttons the same NAME.
That's because only one option can be selected with Radio Buttons. Because the user can select
more than one option with Checkboxes, it makes sense to give them different NAME values, and
treat them as separate entities (but some advocate treating them just like Radio Buttons).
In your PHP code, the technique is to check whether each checkbox element has been checked or
not. It's more or less the same as for the radio Buttons. First we set up five variable and set them
all the unchecked, just like we did before:
$ch1 = 'unchecked';
$ch2 = 'unchecked';
$ch3 = 'unchecked';
$ch4 = 'unchecked';
$ch5 = 'unchecked';
The next thing is the same as well: check to see if the Submit button was clicked:
if (isset($_POST['Submit1'])) {
Page 75 of 251
Inside of this code, however, we have another isset( ) function:
if ( isset($_POST['ch1']) ) {
This time, we're checking to see if a checkbox was set. We need to do this because of a
peculiarity of HTML checkboxes. If they are not ticked, they have no value at all, so nothing is
returned! If you try the code without checking if the checkboxes are set, then you'll have to deal
with a lot of "Undefined" errors.
If the checkbox is ticked, though, it will return a value. And so the isset( ) function will be true.
If the isset( ) function is true, then our code inside of the if statement gets executed:
if ($ch1 == 'net') {
$ch1 = 'checked';
This is yet another If Statement! But we're just checking the value of a variable. We need to
know what is inside of it. This one says, "If the value inside of the variable called $ch1 is 'net'
then execute some code.
The code we need to execute is to put the text 'checked' inside of the variable called $ch1. The
rest of the if statements are the same – one for each checkbox on the form.
The last thing we need to do is to print the value of the variable to the HTML form:
Again, this is the same code you saw with the Radio Buttons. The PHP part is:
So we're just printing what is inside of the variable called $ch1. This will either be "unchecked"
or "checked",
There are other solution for checkboxes, but none seem simple! The point here, though, is that to
get the job done we used Conditional Logic.
Page 76 of 251
How to validate checkboxes using JavaScript
Another way to deal with checkboxes, though, is with some JavaScript. The following script was
sent to us by Tapan Bhanot. It uses JavaScript to validate the checkboxes before sending it to a
PHP script. Note how the checkboxes all have the same name on the HTML form, and that it is
being posted to a PHP script called step2.php:
VALIDATION OF FORM
<html>
<head>
if (document.getElementsByName('chkboxes')[i].checked) {
if (boxesTicked == "") {
alert ("You must select a box to continue.")
return false
}
else {
alert (boxesTicked)
return true;
}
</script>
Page 77 of 251
<title>Javascript that validates checkboxes</title>
</head>
<body>
</body>
</html>
Page 78 of 251
PHP For Loops
So what’s a loop then? A loop is something that goes round and round. If I told you to move a
finger around in a loop, you’d have no problem with the order (unless you have no fingers!) In
programming, it’s exactly the same. Except a programming loop will go round and round until
you tell it to stop. You also need to tell the programme two other things - where to start your
loop, and what to do after it’s finished one lap (known as the update expression).
You can programme without using loops. But it’s an awful lot easier with them. Consider this.
$answer = 1 + 2 + 3 + 4;
print $answer;
Fairly simple, you think. And not much code, either. But what if you wanted to add up a
thousand numbers? Are you really going to type them all out like that? It’s an awful lot of
typing. A loop would make life a lot simpler. You use them when you want to execute the same
code over and over again.
We'll discuss a few flavours of programming loops, but as the For Loop is the most used type of
loop, we'll discuss those first.
For Loops
Here’s a PHP For Loop in a little script. Type it into new PHP script and save your work. Run
your code and test it out.
<?PHP
$counter = 0;
$start = 1;
$counter = $counter + 1;
print $counter . "<BR>";
?>
Page 79 of 251
How did you get on? You should have seen the numbers 1 to 10 printed on your browser page.
The first thing you need to do is type the name of the loop you’re using, in this case for. In
between round brackets, you then type your three conditions:
Start Value
The first condition is where you tell PHP the initial value of your loop. In other words, start the
loop at what number? We used this:
$start = 1;
We’re assigning a value of 1 to a variable called $start. Like all variables, you can make up your
own name. A popular name for the initial variable is the letter i . You can set the initial condition
before the loop begins, like we did:
$start = 1;
Or you can assign your loop value right in the For Loop code:
The result is the same – the start number for this loop is 1
End Value
Next, you have to tell PHP when to end your loop. This can be a number, a Boolean value, a
string, etc. Here, we’re telling PHP to keep going round the loop while the value of the variable
$start is Less Than 11.
When the value of $start is 11 or higher, PHP will bail out of the loop.
Update Expression
Loops need a way of getting the next number in a series. If the loop couldn’t update the starting
value, it would be stuck on the starting value. If we didn’t update our start value, our loop would
Page 80 of 251
get stuck on 1. In other words, you need to tell the loop how it is to go round and round. We used
this:
$start++
In a lot of programming language (and PHP) the double plus symbol (++) means increment
(increase the value by one). It’s just a short way of saying this:
$start = $start + 1
You can go down by one (decrement) by using the double minus symbol (--), but we won’t go
into that.
So our whole loop reads “Starting at a value of 1, keep going round and round while the start
value is less than 11. Increase the starting value by one each time round the loop.”
Every time the loop goes round, the code between our two curly brackets { } gets executed:
$counter = $counter + 1;
print $counter . "<BR>";
Notice that we’re just incrementing the counter variable by 1 each time round the loop, exactly
the same as what we’re doing with the start variable. So we could have put this instead:
$counter ++
The effect would be the same. As an experiment, try setting the value of $counter to 11 outside
the loop (it’s currently $counter = 0). Then inside the loop, use $counter- - (the double minus
sign). Can you guess what will happen? Will it crash, or not? Or will it print something out?
Better save your work, just in case!
To get more practice with the For Loop, we'll write a little Times Table programme.
Page 81 of 251
A PHP Times Table Programme
In the previous part, you saw what a For Loop was. In this section, we'll write a times table
programme to illustrate how for loops work.
There's a script called timesTable.php amongst the files you downloaded (in the scripts folder).
When loaded into the browser, it looks like this:
There's a script called timesTable.php amongst the files you downloaded (in the scripts folder.).
When loaded into the browser, it looks like this:
What we're going to do is to get the values from the textboxes and create a Times Table
proramme. When the button is clicked, the output will be something like this:
In other words, when the button is clicked we'll print the Times Table to the page. You can have
a different Times Table, depending on what values you enter in the textboxes. To make a start
with the coding, move on to the next part.
Page 82 of 251
Code for a PHP Times Table
The code for the Times Table in the previous page uses a For Loop. The Start for the loop will
come from the Start Number textbox, and the end of the loop will come from the End Number
textbox. Here's the code in full (without the HTML):
<?PHP
$times = 2;
if (isset($_POST['Submit1'])) {
$start = $_POST['txtStart'];
$end = $_POST['txtEnd'];
$times = $_POST['txtTimes'];
?>
Code Explanation
We need all those numbers from the textboxes on the form, so we start with:
$times = 2;
if (isset($_POST['Submit1'])) {
$start = $_POST['txtStart'];
$end = $_POST['txtEnd'];
$times = $_POST['txtTimes'];
Page 83 of 251
The first line just puts a value in the variable called $times . This is so that the "Multiply By"
textbox will have a default value when the page is loaded.
Next we use the isset( ) function again, just to check if the user clicked the Submit button. This is
exactly the same as you saw in the last section.
$start = $_POST['txtStart'];
$end = $_POST['txtEnd'];
$times = $_POST['txtTimes'];
Again, this is code you met in the last section. You just assign the values from the textboxes to
the new variables using $_POST[]. In between the square brackets, we've typed the NAME of
the HTML textboxes. So this gives us the values that the user entered on the form. Next comes
out For Loop:
So we have a starting value for our loop, an end value, and an update expression. The starting
value is coming from the variable called $start. This will be whatever number the user entered in
the first textbox. The default is 1. Look at the end value, though:
The end value is when the value in the variable called $start is less than or equal to the value held
in the variable called $end. This works because we're increasing the value of $start each time
round the loop. The variable called $end is a fixed value, and comes from the textbox on the
form.
The last part of the loop code is the update expression. This tells PHP to increase the value of
$start each time round the loop:
$start++
The double plus symbol (++) means "add 1 to the number held in $start".
Page 84 of 251
And that's the essence of for loops: provide a start value, an end value, and how you want to
update each time round the loop.
The code inside the for loop, however, the code that gets executed each time round the loop, is
this:
Remember, the variable $times holds the times table, the 2 times table by default. This is being
multiplied by whatever is inside the variable $start. Each time round the loop, $start will have a
different value – first 1, then 2, then 3, etc. The answer is then stored in the variable that we
called $answer. So it's really doing this:
$answer = 1 * 2;
$answer = 2 * 2;
$answer = 3 * 2;
etc
print $start . " multiplied by " . $times . " = " . $answer . "<BR>";
This is just concatenation. See if you can work out what all the parts do!
And that’s it – your very own times table generator. If you have children, show them the
programme you wrote. They’ll be very impressed and tell you how brilliant you are. Children are
like that.
Of course, your programme is not perfect, which I’m sure the children will discover. Especially
if they enter a 10 as the start number and a 1 as the end number. Why doesn't it print anything
out? Anything you can do to trap this error? Another if statement somewhere, perhaps?
Page 85 of 251
PHP While Loops
Instead of using a for loop, you have the option to use a while loop. The structure of a while loop
is more simple than a for loop, because you’re only evaluating the one condition. The loop goes
round and round while the condition is true. When the condition is false, the programme breaks
out of the while loop. Here’s the syntax for a while loop:
while (condition) {
statement
And here’s some code to try. All it does is increment a variable called counter:
$counter = 1;
The condition to test for is $counter < 11. Each time round the while loop, that condition is
checked. If counter is less than eleven then the condition is true. When $counter is greater than
eleven then the condition is false. A while loop will stop going round and round when a
condition is false.
If you use a while loop, be careful that you don’t create an infinite loop. You’d create one of
these if you didn’t provide a way for you condition to be evaluated as true. We can create an
infinite loop with the while loop above. All we have to do is comment out the line where the
$counter variable is incremented. Like this:
$counter = 1;
Page 86 of 251
Notice the two forward slashes before $counter++. This line will now be ignored. Because the
loop is going round and round while counter is less than 11, the loop will never end – $counter
will always be 1.
Here’s a while loop that prints out the 2 times table. Try it out in a script.
$start = 1;
$times = 2;
$answer = 0;
The while loop calculates the 2 times tables, up to a ten times 2. Can you see what’s going on?
Make sure you understand the code. If not, it’s a good idea to go back and read this section
again. You won’t be considered a failure. Honest!
In the next part, we'll have a brief look at Do ... While loops
Page 87 of 251
PHP Do ... While loops
This type is loop is almost identical to the while loop, except that the condition comes at the end:
do
statement
while (condition)
The difference is that your statement gets executed at least once. In a normal while loop, the
condition could be met before your statement gets executed.
Don’t worry too much about do … while loops. Concentrate on For loops and While loops. But
there is another type of loop that comes in handy - the For Each loop. First, a quick word about
the break statement.
Page 88 of 251
The PHP break statement
There are times when you need to break out of a loop before the whole thing gets executed. Or,
you want to break out of the loop because of an error your user made. In which case, you can use
the break statement. Fortunately, this involves nothing more than typing the word break. Here’s
some not very useful code that demonstrates the use of the break statement:
$TeacherInterrupts = true;
$counter = 1;
if ($TeacherInterrupts == true) {
break;
$counter++;
Ok, that's enough of loops. For now. In the next section, we'll take a look at what arrays are, and
how useful they can be. (Yes, there'll be loops!)
Page 89 of 251
PHP Arrays
You know what a variable is – just a storage area where you hold numbers and text. The problem
is, a variable will hold only one value. You can store a single number in a variable, or a single
string. An array is like a special variable, which can hold more than one number, or more than
one string, at a time. If you have a list of items (like a list of customer orders, for example), and
you need to do something with them, then it would be quite cumbersome to do this:
What if you want to loop through your orders and find a specific one? And what if you had not
four orders but four hundred? A single variable is clearly not the best programming tool to use
here. But an array is! An array can hold all your orders under a single name. And you can access
the orders by just referring to the array name.
If that's a bit confusing right now, let’s make a start on explaining how arrays work.
Page 90 of 251
How to Set up a PHP Array
In the code on the previous page, we had four items, and all with a different variable name:
$Order_Number1, $Order_Number2, $Order_Number3, and $Order_Number4. With an
array, you can just use a single name. You set up an array like this:
$Order_Number = array( );
First you type out what you want your array to be called ($Order_Number, in the array above)
and, after an equals sign, you type this:
array( );
So setting up an array just involves typing the word array followed by a pair of round brackets.
This is enough to tell PHP that you want to set up the array. But there's nothing in the array yet.
All we're doing with our line of code is telling PHP to set up an array, and give it the name
$Order_Number.
You can use two basic methods to put something into an array.
The first method involves typing your values between the round brackets of array(). In the code
below, we're setting up an array to hold the seasons of the year:
So the name of the array is $seasons. Between the round brackets of array(), we have typed some
values. Each value is separated by a comma:
Arrays work by having a position, and some data for that position. In the above array, "Autumn"
is in position zero, "Winter" is in position 1, "Spring" is in position 2, and "Summer" is in
position 3.
The first position is always zero, unless you tell PHP otherwise. But the position is know as a
Key. The Key then has a value attached to it. You can specify your own numbers for the Keys. If
so, you do it like this:
$seasons = array( 1 => "Autumn", 2 => "Winter", 3 => "Spring", 4 => "Summer" );
Page 91 of 251
So you type a number for your key, followed by the equals sign and a right angle bracket ( => ).
In the array above, the first Key is now 1 and not 0. The item stored under key 1 is "Autumn".
The last key is 4, and the item stored under key 4 is "Summer". Careful of all the commas, when
you set up an array like this. Miss one out and you'll get error messages. Here's the keys and
values that are set up in the array above:
1=> "Autumn",
2=> "Winter",
3=> "Spring",
4=> "Summer"
If you let PHP set the keys for you, it would be this:
0=> "Autumn",
1=> "Winter",
2=> "Spring",
3=> "Summer"
You can have numbers for the values of your keys. Here's an array that stores the numbers 10,
20, 30 and 40.
Because no keys were specified, PHP will set your array up like this:
0=> 10,
1=> 20,
2=> 30,
3=> 40
Here's the same array again, only this time we're specifying our own key:
$Array_Name = array(1 => 10, 2 => 20, 3 => 30, 4 => 40);
1=> 10,
2=> 20,
3=> 30,
4=> 40
So the key name is typed before the => symbol, and the data stored under this key is to the right.
$Array_Name = array(1 => 10, 2 => "Spring", 3 => 30, 4 => "Summer");
Page 92 of 251
The above array would then look like this:
1=> 10,
2=> "Spring",
3=> 30,
4=> "Summer"
$seasons = array();
$seasons[ ]="Autumn";
$seasons[ ]="Winter";
$seasons[ ]="Spring";
$seasons[ ]="Summer";
Here, the array is first set up with $seasons = array();. This tells PHP that you want to create an
array with the name of $seasons. To store values in the array you first type the name of the array,
followed by a pair of square brackets:
$seasons[ ]
After the equals sign, you type out what you want to store in this position. Because no numbers
were typed in between the square brackets, PHP will assign the number 0 as the first key:
0=> "Autumn",
1=> "Winter",
2=> "Spring",
3=> "Summer"
This is exactly the same as the array you saw earlier. If you want different numbers for your
keys, then simply type them between the square brackets:
$seasons[1]="Autumn";
$seasons[2]="Winter";
$seasons[3]="Spring";
$seasons[4]="Summer";
1=> "Autumn",
2=> "Winter",
Page 93 of 251
3=> "Spring",
4=> "Summer"
This method of creating arrays can be very useful for assigning values to an array within a loop.
Here's some code:
$start = 1;
$times = 2;
$answer = array();
Don't worry if you don't fully understand the code above. The point is that the values in the array
called $answer, and the array key numbers, are being assigned inside the loop. When you get
some experience with arrays, you'll be creating them just like above!
In the next part, we'll take a look at how to get at the values stored in your arrays.
OK, so you now know how to store values in your array. But how do you get at those values?
Well, there are few ways you can do it. But the "Key" is the key. Here's an example for you to
try:
<?php
?>
Page 94 of 251
The array is the same one we set up before. To get at what is inside of an array, just type the key
number you want to access. In the above code, we're printing out what is held in the 0 position
(Key) in the array. You just type the key number between the square brackets of your array
name:
print $Array_Name[0];
$key_data = $Array_Name[0];
print $key_data;
It's a lot easier using a loop, though. Suppose you wanted to print out all the values in your array.
You could do it like this:
print $seasons[0];
print $seasons[1];
print $seasons[2];
print $seasons[3];
print $seasons[$key_Number];
If you have many array values to access, then using a loop like the one above will save you a lot
of work!
You don't have to use numbers for the keys - you can use text. We'll see how to do that in the
next part.
Page 95 of 251
Your arrays keys don't have to be numbers, as in the previous section. They can be text. This can
help you remember what's in a key, or what it's supposed to do. When you use text for the keys,
you're using an Associative array; when you use numbers for the keys, you're using a Scalar
array. Here's an array that sets up first name and surname combinations:
$full_name = array( );
$full_name["David"] = "Gilmour";
$full_name["Nick"] = "Mason";
$full_name["Roger"] = "Waters";
$full_name["Richard"] = "Wright";
Fans of a certain band will know exactly who these people are! But look at the keys and values
now:
0 => "Gilmour",
1 => "Mason",
2 => "Waters",
3 => "Wright"
To access the values in an Associative array, just refer to the Key name:
print $full_name["David"];
However, because Associative arrays don't have numbers for the keys, another technique is used to loop
round them – the For Each loop. We'll see how they work in the next part.
In the previous section, you saw what a Associative array was, and that they use text as the Key.
In this lesson, you'll learn how to access each element in Associative array - with the For Each
loop. So study the following code (try it out in a script):
Page 96 of 251
$full_name = array( );
$full_name["David"] = "Gilmour";
$full_name["Nick"] = "Mason";
$full_name["Roger"] = "Waters";
$full_name["Richard"] = "Wright";
The For Each loop is a little more complex than other loops you've met. In the script above, we
set up the array as normal. But the first line of the loop is this:
Notice that the name of the loop is one word: foreach and NOT for each. Next comes the round
brackets. Inside of the round brackets, we have this:
You start by typing the name of the array you want to loop round. For us, that was $full_name.
Next is this:
This means, "Get the Key and its Value from the array called $full_name. The Key is called
$key_name in the script above, and the value is called $key_value. But these are just variable
names. You can call them almost anything you like. Would could have had this:
When you use foreach, PHP knows that it's accessing the key name first and then the key value.
It knows this because of the => symbol between the two. It then returns the values into your
variable names, whatever they may be.
Once your loop code is executed (a print statement for us), it then loops round and returns the
next Key/Value pair, storing the results in your variables.
If you need to access values from an Associative array, then, use a foreach loop.
In the next few sections, you'll see some useful things you can do with arrays.
Page 97 of 251
Sorting PHP Array values
There may be times when you want to sort the values inside of an array. For example, suppose
your array values are not in alphabetical order. Like this one:
$full_name = array();
$full_name["Roger"] = "Waters";
$full_name["Richard"] = "Wright";
$full_name["Nick"] = "Mason";
$full_name["David"] = "Gilmour";
To sort this array, you just use the assort( ) function. This involves nothing more complex than
typing the word asort, followed by round brackets. In between the round brackets, type in the
name of your Associative array:
asort( $full_name );
The letter "a" tells PHP that the array is an Associative one. (If you don't have the "a" before
"sort", your key names will turn in to numbers!). The "a" also tells PHP to sort by the Value, and
NOT by the key. In our script above, the surnames will be sorted. If you want to sort using the
Key, then you can use ksort() instead.
If you have a Scalar array (numbers as Keys), then you leave the "a" off. Like this:
$numbers = array( );
$numbers[ ]="2";
$numbers[ ]="8";
$numbers[ ]="10";
$numbers[ ]="6";
sort($numbers);
print $numbers[0];
print $numbers[1];
print $numbers[2];
print $numbers[3];
The numbers are then sorted from lowest to highest. If you want to sort in reverse order then you
need the following:
Page 98 of 251
rsort( ) – Sorts a Scalar array in reverse order
arsort( ) - Sorts the Values in an Associative array in reverse order
krsort( ) - Sorts the Keys in an Associative array in reverse order
In the next part, we look at how to get a random value from an array.
You can grab a random key from an array. This could be useful in games of chance. Here's a
simple script that simulates a single dice throw:
<?PHP
?>
array_rand($numbers, 1);
You start off with the function array_rand( ). In between the round brackets, you need two
things: the name of your array, and how many random keys you want to grab.
Try the script out. Refresh the page and you should see a different number between 1 and 6
display.
In the next part, we'll see how the count function works when applied to an array.
The count( ) function is useful when you want to return how many elements are in your array.
You can then use this in a for loop. Here's an example we used earlier, only this time with the
count function:
Page 99 of 251
$array_count = count($seasons);
print $seasons[$key_Number];
$array_count = count($seasons);
So you type the word count and then the round brackets. In between the round brackets, you type
the name of your array. The function then counts how many elements are in the array, which we
then assign to a variable called $array_count. You can then use this value as the end condition
in you loop:
Here, we're saying, "keep looping round as long as the value in $key_Number is less than the
value in $array_count.
To round off this section on arrays, there are some script for you to try out in the next part.
To give your more practice using arrays, there are some scripts for you to try out. The scripts are
amongst the files you downloaded (in the scripts folder). The file you're looking for is called
scripts.txt. You can also copy and paste the scripts by clicking on the links below.
The ability take strings of text and manipulate them is one of the essential abilities you need as a
programmer. If a user enters details on your forms, then you need to check and validate this data.
For the most part, this will involve doing things to text. Examples are: converting letters to
uppercase or lowercase, checking an email address to see if all the parts are there, checking
which browser the user has, trimming white space from around text entered in a text box. All of
these come under the heading of string manipulation. To make a start, we'll look at changing the
case of character.
Suppose a you have a textbox on a form that asks users to enter a first name and surname. The
chances are high that someone will enter this:
bill gates
Instead of this:
Bill Gates
So your job as a programmer is to convert the first letter of each name from lower to uppercase.
This is quite easy, with PHP.
There's a script amongst the files you downloaded called changeCase.php. Open up this page to
see the code.
It's just a textbox and a button. The textbox will already have "bill gates" entered, when you load
it up. What we want to do is to change it to "Bill Gates" when the button is clicked. Here's the
script that does that.
if (isset($_POST['Submit1'])) {
$full_name = $_POST['username'];
$full_name = ucwords( $full_name );
?>
The first line just makes sure that the lowercase version is placed into the textbox when the page
loads:
This is the line that we want to convert and turn in to "Bill Gates". The only line in the code that
you haven't yet met is this one:
And that's all you need to convert the first letter of every word to uppercase! The inbuilt function
is this:
ucwords( )
In between the round brackets, you type the variable or text you want to convert. PHP will take
care of the rest. When the conversion is complete, we're storing it back into the variable called
$full_name.
If you just want to convert the first letter of a string (for a sentence, for example), then you can
use ucfirst( ) . Like this:
strtoupper( )
strtolower( )
Again, the variable or text you want to change goes between the round brackets of the function.
This is then assigned to a variable.
In the next part, we'll take a look at how to trim unwanted white space from your strings
Another thing you'll want to do is to trim the white (blank) space from text entered into
textboxes. This is quite easy, as there's some useful PHP functions to help you do this.
From the quotation marks, we can see that there is extra space before and after the text. We can
count how many characters this string has with another useful function: strlen( ). As its name
suggests, this returns the length of a string, By length, we mean how many characters a string
has. Try this script:
<?PHP
$letCount = strlen($space);
print $letCount;
?>
When you run the script, you'll find that the variable contains 14 characters. However, username
has only 8 characters. If you're checking for an exact match, this matters!
To remove the white space, you can use the trim( ) function. Change your script to this:
<?PHP
?>
When you run the script now, you should find that the variable has the correct number of
characters - 8. That's because the trim( ) function removes any blank spaces from the left and
right of a string.
Two related function are ltrim( ) and rtrim( ). The first one, ltrim( ), removes space from the
beginning of a string; the second one, rtrim( ), removes space from the end of a string. You can
also use these two functions to trim unwanted characters, as we do much later in the book for the
forum walkthrough.
In the next part, we'll take a quick look at the shuffle function.
A rather fun function you can use is str_shuffle( ). What this does is to shuffle all the characters
in a string. You can use this to create a quick anagram programme. Try this script:
<?PHP
$full_name = 'anagram';
$full_name = str_shuffle($full_name);
print $full_name;
?>
Only three lines long, but the function takes a variable or direct text and shuffles the characters
around.
Next up, something a little more useful - Finding one string inside of another.
A more useful thing you'll want to do is to see if one string is inside of another. For example, you
can get which browser the user has with this:
$agent = $_SERVER["HTTP_USER_AGENT"];
print $agent;
Try it out and see what gets printed out. You should find that quite along string gets printed.
If you're testing which browser the user has, you can use a string function to search for a short
string inside of this very long one. A PHP string function you can use is strpos( ). The syntax for
the strpos function is:
You need to supply at least the first two. The third, start, is optional. Here's a simple example.
When you run the script, a value of 0 is returned. That's because PHP considers the first
character of the string to be at position 0, the second character at position 1, the third at position
2, etc. Since we were searching for the letter "b", and "bill gates" begins with this letter, a value
of 0 is returned.
to this:
What happens when you run the script? Nothing! At least, you don't get a value back. That's
because if strpos can't find your characters, it returns a value of false. A value of false in PHP
can be tested for by using the triple equals operator. Like this:
The triple equals operator ( === ) not only checks for a value but what type of value it is: integer,
string, Boolean, etc. If a string is not found, you need to use this operator, just in case the
character you're searching for is at position 0. PHP is a little bit quirky with zeros. It seems them
as having a false value as well. But it can be a different kind of false! So use ===.
$agent = $_SERVER['HTTP_USER_AGENT'];
}
else if (strpos(strtoupper($agent), 'FIREFOX')) {
print "Firefox";
}
else {
print $agent;
The above script uses two of the string functions that you've met: strpos( ) and strtoupper( ).
See if you can figure out what's going on!
In the next part, you'll learn how to split a line of text. You'll need to do this when working with,
for example, text files.
PHP allows you to split a line of text into its component parts. For example, if you were reading
from a text file line by line you might have to break apart a line like this:
If this were a poll, and you want to display the results for all to see, then you might be trying to
print something like this on the page:
Poll Number 1
Respondents: 1500
Answer A: 250
Answer B: 150
Answer C: 100
Answer D: 1000
The line of text is separated by commas. As the line is read in (which we'll see how to do in a
later section), you'd be passing it to a variable. You'd then need to chop the text up, based on the
comma. We can simulate that. First, pass the text to a variable:
The next job is to split this text apart, so that PHP knows about all the separate pieces. The
pieces we want are:
Poll number 1
1500
250
150
100
1000
To split lines of text, the gloriously sounding explode( ) function can be used. You just provided
it with the text you want to split, and the character that is used to separate each piece. Here's the
syntax:
In between the round brackets of explode( ) the separator you want to use goes first, followed by
a comma, then the string you want to split. For our line of code above, you'd do this:
To get at the pieces of the array, access it in the normal manner. Here's some code to try:
<?PHP
print $text_line[0];
?>
Run the code and see what happens. Then change the 0 of the print statement to 1, then to 2, then
to 3, then to 4, then to 5, and finally to 5. What happens when you enter 6 as the array Key
number?
To see all the parts of your array, you can use a different form of print statement. Try changing
the print line in your code from this:
print $text_line[0];
to this:
print_r($text_line);
You should see your array details printed out, with all the Keys and the Values. The print_r( )
statement is quite useful, when you're trying to debug your code.
And it does show that explode( ) works – all of the values are in an array!
Another way to access all the element returned by explode( ) is with a for loop:
We use the count( ) function to get the number of elements in the array called $text_line. Each
time round the loop, PHP checks to see if the value in the variable called $start is less than how
many elements are in the array. It breaks out of the loop when $start is NOT less than
count($text_line).
$text_line[$start]
The variable called $start will be different each time round the loop. So the value at each
position is printed. The "<BR>" at the end just adds a HTML line break.
As well as exploding a line of text, you'll need to know how to join the parts back together again.
We'll do that in the next part.
In the previous PHP lesson, you'll learnt how to split a line of text. All the parts of the line of text
will then be in an array.
But if you have a line of text in an array, you can join it all together to form a single line of text.
This is just the opposite of explode. This time, use implode( ):
Here we have an array called $seasons. The text in the array needs to be joined before writing it
back to a text file. The implode( ) function does the joining. The syntax for the implode( )
function is just the same as explode( ).
Even a space:
The implode( ) function can come in handy, if you need to work with single lines of text.
Escaping in PHP doesn't mean breaking free and "doing a runner". It is a technique to prevent
PHP from ending your strings too early, or for making sure you have the correct string
information returned. Here's an example. Try this script:
<?PHP
?>
Make sure you type the script exactly as it is, with all the single quote marks. Now run the script.
What you should find is that PHP gives you an error message. The reason is that you have three
single quote marks. PHP gets confused, because it doesn't know what your string is. To solve the
problem, you could use double quotes on the outside. Like this:
Or you could escape the apostrophe. You escape a character by typing a "slash" before it. Like
this:
If you try that out, you should find that the string prints correctly.
<?PHP
$astring = 'mypath\';
print $astring;
?>
Again, you'll get an error from PHP. Surround it with double quotes instead of single quotes and
run the script again. Does the string print?
The reason it doesn't is because you haven't escaped the slash. PHP sees it as a special character,
and is expecting more details after the slash. But we want a slash in the string. To escape it, use
another slash. Like this:
$astring = 'mypath\\';
So now we have two slashes on the end of the string. When you run the script, you should find
that it prints out this:
mypath\
If your PHP script is not returning the characters it should do, then you may need to use the slash
to escape them.
You also need to escape certain characters when working with databases, otherwise, you're
opening yourself up to attack! You'll hear more on this topic when we get to that section.
In the next part, we'll have a list of string functions that may come in handy, and an example of
how to use each one.
Instead of detailing all the possible string functions you can use, we'll just give you a brief list.
(There's loads of them!) There's an example of how to use each string function, if you click on
the links below. Just dip in to them as and when needed.
Some more examples of string functions can be found on these external sites:
http://php.net/manual/en/ref.strings.php
In the next section, we'll take a look at PHP Functions: what they are, and how to create your
own.
You've been working with string functions in the last section, and references to functions have
been made in other sections. But what is a function, and how do you create them? In this section,
you'll find out.
What is a Function?
A function is just a segment of code, separate from the rest of your code. You separate it because
it's nice and handy, and you want to use it not once but over and over. It's a chunk of code that
you think is useful, and want to use again. Functions save you from writing the code over and
over. Here's an example.
"Bill Gates"
But you also want to check if the user entered any text at all. You don't want the textbox to be
completely blank!
You can use the PHP inbuilt function called trim( ). Like this:
That will get rid of the white space in the text box. But it won't check if the text box is blank.
You can add an if statement for that:
if ($user_text == "") {
But what if you have lots of textboxes on your form? You'd have to have lots of if statements,
and check each single variable for a blank string. That's a lot of code to write!
Rather than do that, you can create a single function, with one if statement that can be used for
each blank string you need to check. Using a function means there's less code for you to write.
And it's more efficient. We'll see how to write a function for the above scenario in a moment.
But first, here's the basic syntax for a function.
function function_name() {
So you start by typing the word function. You then need to come up with a name for your
function. You can call almost anything you like. It's just like a variable name. Next, you type two
round brackets ( ). Finally, you need the two curly brackets as well { }. Whatever you function
does goes between the curly brackets. Here's a simple example that just print something out:
function display_error_message() {
In the example above, we've started with function. We've then called this particular function
display_error_message. In between the curly brackets, there a print statement. Try it out with
this script:
<?PHP
function display_error_message( ) {
?>
Run your script and see what happens. You should find that nothing happens!
The reason that nothing happened is because a function is a separate piece of code. It doesn't run
until you tell it to. Just loading the script won't work. It's like those inbuilt functions you used,
such as trim. You can't use trim( ) unless you type out the name, and what you want PHP to
trim. The same applies to your own functions – you have to "tell" PHP that you want to use a
function that you wrote. You do this by simply typing out the name of your function. This is
known as "calling" a function. Try this new version of the script.
<?PHP
function display_error_message() {
display_error_message( );
?>
After the function, we've typed out the name again. This is enough to tell PHP to run our code
segment. Now change your code to this, and see what happens:
<?PHP
display_error_message();
function display_error_message() {
?>
When you run the code, you should see no difference – the function will still get executed with
the name above or below the function. But for neatness and readability's sake, it's better to put all
of your function either at the top or bottom of your scripts. Or better yet, in a separate PHP file.
You can then use another inbuilt function called "Include" (which we'll get to soon)
There's a thing called scope in programming. This refers to where in your scripts a variable can
be seen. If a variable can bee seen from anywhere, it's said to have global scope. In PHP,
variables inside of functions can't be seen from outside of the function. And functions can't see
variables if they are not part of the function itself. Try this variation of our script as an example:
<?PHP
display_error_message();
function display_error_message( ) {
print $error_text;
?>
This time, we have set up a variable called $error_text to hold the text of our error message.
This is set up outside of the function. Run the script, and you'll get a PHP error message about "
Undefined variable".
<?PHP
print $error_text;
function display_error_message() {
?>
This time, the variable is inside the function, but we're trying to print it from outside the
function. You still get an error message. Here's a correct version:
<?PHP
display_error_message();
function display_error_message() {
?>
Here, we have both the variable and the print statement set up inside of the function. The error
message now prints.
So if you need to examine what is inside of a variable, you need a way to get the variable to the
function. That's where arguments come in. We'll explore arguments in the next part.
In the previous two sections, you saw how to set up your own functions, and the importance of
Scope. In particular, you learnt that you need a handy way to pass values to your function. That's
where arguments come in.
Functions can be handed variables, so that you can do something with what's inside of them. You
pass the variable over to your functions by typing them inside of the round brackets of the
function name. Here's a script similar to the one you saw earlier:
<?PHP
function display_error_message($error_text) {
print $error_text;
?>
The only difference is the that we now have something between the round brackets of our
function:
function display_error_message($error_text) {
The name is the same, but we've put a variable in between the round brackets. This is the
variable that we want to do something with. The one called $error_text. By typing a variable
inside of the round brackets, you are setting up something called an argument. An argument is a
variable or value that you want your function to deal with.
The first line puts something into the variable. But when you want to hand something to a
function that has an argument, you need to type it between the round brackets of the function
call. In our script, we're typing the name of the variable. But this would do just as well:
display_error_message("Error message");
Here, we're putting direct text between the round brackets. That works ok. But try it like this:
That's telling you that your function has been set up to take an argument, but that you've left the
round brackets empty when you tried to call the function.
Your functions can have more than 1 argument. Just separate each argument with a comma. Like
this:
error_check($error_text, error_flag);
If you only hand the above function 1 argument, you'd get error messages from PHP.
So, to recap:
In the next part, you'll see a function that checks for blank text boxes. The function has 1
argument.
If you remember the script that we wanted to create earlier it was this:
So we want to check that the textbox doesn't just contain this "". There has to be something in it,
like "Bill Gates". Here's a script that does all three items on our list:
display_error_message($user_text);
function display_error_message($user_text) {
if ($user_text == "") {
}
else {
?>
Try it out. When you run the script, you should find that Text OK prints. Now change this line:
to this:
$user_text = trim("");
Run your script again. This time, Blank text box detected should print out. Obviously, we're not
getting the text from a textbox on a form, but just simulating the process. If you want to try out a
version with all the HTML, here it is. This next script checks two textboxes on a form.
Try the script out. But the point is, that we're using the same function to check for blank text
boxes. We're not writing the same code over and over. Just call our one function as and when
needed.
In the next part, we'll see how to get values back out of functions.
When you're creating your own functions, you may notice that they can be broken down in to
two categories: functions that you can leave, and just let them do their jobs; and functions where
you need to get an answer back. As an example, here's the two different categories in action:
The print function is an example of a function that you can leave, and just let it do its job. You
just tell it what to print and it gets on with it for you. But a function like strlen( ) is not. You
need something back from it – the length of the string.
Suppose you had a function that worked out a 10 percent discount. But you only want to apply
the discount if the customer spent over 100 pounds. You could create a function that is handed
the amount spent. Then check to see if it's over a 100 pounds. If it is, the function calculates the
discount; if not, don't apply the discount. But in both cases, you want the function to return the
answer to your question – What do I charge this customer? Here's the script:
<?PHP
$total_spent = 120;
$order_total = calculate_total($total_spent);
print $order_total;
function calculate_total($total_spent) {
$discount = 0.1;
}
else {
$total_charged = $total_spent;
return $total_charged;
?>
The lines to concentrate on are the ones for the $total_spent variable. The code first sets up a
total amount spent, which in practice may come from a form on a text box, or a hidden field:
$total_spent = 120;
$order_total = calculate_total($total_spent);
The function call is now on the right of the equals sign ( = ). To the left of the equals sign is just
a normal variable - $order_total . If you're setting up your function like this then you are asking
PHP to return a value from your functions, and put the answer into a variable on the left of the
equals sign. PHP will go off and calculate your function. When it's found an answer, it will try to
return a value. The answer will be stored in the name of your function, calculate_total( ) for us.
But look at the function itself, and the line at the end:
function calculate_total($total_spent) {
$discount = 0.1;
}
else {
$total_charged = $total_spent;
return $total_charged;
return $total_charged;
The return word tells PHP to return a value. The value it returns is whatever you have stored in
the variable that comes after the word return. Here, were telling PHP to set the answer to the
If you're finding this a bit tricky, remember what a function is: a separate piece of code that does
some work for you. It can either return a value, or not return a value. It depends entirely on your
needs. But don't worry about the majority of the code above – just concentrate on the coloured
parts.
In the script above, you'd want to get something back from the function, rather than letting it just
print something out. If you ran the previous script, you'll notice that the function prints out the
same thing twice. To stop that happening, we can get a return value, and put it in a variable. We
can then check what is coming back from the function, to check what's in it.
In the next part, we'll take a look at some other aspects of functions.
By Ref, By Val
Functions can be quite hard to get used, if you've never met them before. Another difficult part to
understand is how values can change, or not change, depending on scope. Scope, if you recall,
refers to where in your code a variable can be seen. If you just do this, for example:
$Variable_Value = 10;
example( );
function example() {
print $Variable_Value;
then you'll get a PHP error about "undefined variable". That's because the function called
example( ) can't see what's inside of the variable called $Variable_Value.
In order for the function to be able to see what’s inside of the variable called $Variable_Value,
you can set up the function to accept an argument. You'd then type the variable name between
the round brackets, when you come to call it. Like this:
<?PHP
function example($Variable_Value) {
print $Variable_Value;
?>
If you run the code above, it now prints out the number ten. But it's important to bear in mind
that you are just handing the function a copy of the variable. You're not effecting the original. As
an example, change your code to this:
<?PHP
$Variable_Value = 10;
example($Variable_Value);
function example($Variable_Value) {
?>
Here, we have three print statement: one before the call to the function, one inside of the
function, and one after the function call. But we're printing out the value of the variable called
$Variable_Value each time. Inside of the function, we're adding ten to the value of the variable.
When you run the code, it will print out this:
The important one is After the function call. Even though we changed the value of
$Variable_Value inside of the function, it still print 10 after the function call! That's because the
function was handed a copy, and NOT the original.
function example(&$Variable_Value) {
The only addition is a & character before the variable between round brackets. This tells PHP
that you want to make changes to the original, and don't just want a copy. When you run the
script, it now print out the following:
After the function call, we now have a value of 20! So a change to the value of the variable
outside the function has been made. When you makes changes to the original like this, it's called
passing the variable by reference (don't just copy it – remember it).
Try not to worry about value and reference. Unless the answers you're getting back from your
function are rather odd, that is!
PHP stores a list of information about the server. This will include things like, the browser the
visitor is using, the IP address, and which web page the visitor came from. Here's a script to try
with those three Server Variables:
$referrer = $_SERVER['HTTP_REFERER'];
$browser = $_SERVER['HTTP_USER_AGENT'];
$ipAddress = $_SERVER['REMOTE_ADDR'];
These are useful if you want to log your stats, or to ban a particular IP address! (If you run the
script on a local machine, you may get an error for the referrer.)
$_SERVER['Server_Variable']
You start with a dollar sign, then an underscore character ( $_ ). Then you add the word
SERVER. In between square brackets, you type the name of the server variable you want to
access. Surround this with either single or double quotes.
Because you are returning a value, you need to put all that on the right hand side of an equals
sign. On the left of the equals sign ( = ), you need a variable to hold the string that is returned.
The server variables are held in an array (associative), so you can use a foreach loop to get a list
of all available ones. Try this script:
<?PHP
?>
What the script does is to loop round all the server variables and print out the keys and values in
the SERVER array.
When you request a web page be brought back to your browser, you're not just bringing back the
web page. You're also bringing back something called a HTTP HEADER. This is some extra
information, such as type of programme making the request, date requested, should it be
displayed as a HTML document, how long the document is, and a lot more besides.
One of the things HTTP HEADER also does is to give status information. This could be whether
the page was found (404 errors), and the location of the document. If you want to redirect your
users to another page, here's an example:
<?PHP
header("Location: http://www.homeandlearn.co.uk/");
<html>
<body>
</body>
</html>
Note how the header code goes before any HTML. If you put header code after the HTML, you'll
get an error along the lines of "Cannot modify header information."
Being able to include other files into your HTML code, or for your PHP scripts, is a useful thing.
The include( ) function allows you do this.
Suppose you have a text file that you want to include in a web page that you've already got up
and running. You could copy and paste the text from the file straight into you HTML. Or you
could use the include( ) function
As an example for you to try, there are two files amongst the ones you downloaded (in the scripts
folder), called include.php and textfile.txt. Load up the one called include.php.
<HTML>
<HEAD>
<TITLE>Include files</TITLE>
</HEAD>
<BODY>
</BODY>
</HTML>
<?PHP
include "textfile.txt";
?>
So in between PHP script tags, type the word include. After the word include, type the name of
the file you want to include on your page. Your filename can either go after a space, and between
quotation marks, or you can put it in round brackets (again, with the quotes).
As well as including text, you can include HTML. This can save you lots of work. For example,
a web page typically contains a menu bar, with links to other areas of your site. Something like
this:
Suppose you decide to add a new section to your site. The new page should be like this:
To see how it works, load up the page called links.php that is among the files you downloaded
(in the scripts folder): you should see the first menu bar. This has the include line, that points to
another file - linksPage.txt (this is also in the scripts folder).
If you open up the text file called linksPage.txt, you'll see that it's just a HTML table. To get this
table into the PHP page called links.php, we just did this:
The point is, if we had the include line on all pages of out site, and we had to add a new section,
we could just change the text file linksPage.txt. This change would then mean that all the pages
in the site would be updated!
Try it yourself. Add the following line to the page called linksPage.txt. Put it between the
TABLE tags:
<TR>
</TD>
</TR>
Save the page, and then load up links.php again. You should see a new section added to your
menu bar.
Including Scripts
You can also use the include( ) function for scripts. You could include those valuable error
checking functions that you've stored in one PHP file. Or just use it to cut down on the amount of
code in the page.
As an example, load up the page called includeScript.php (in the scripts folder that you
downloaded). The code is quite simple. It's just this:
<?PHP
include "myOtherScript.php";
doPrint();
?>
The above script uses include to include another PHP script - myOtherScript.php (also in the
scripts folder). The function called doPrint() is in myOtherScript.php. If you open that file, you'll
see it's just this:
<?PHP
function doPrint() {
?>
Load up the page called includeScript.php in your browser. You should see two lines printed
out.
So, include is a very useful function – one of the most useful inbuilt PHP functions available to
you!
In the next section, we'll look at some of the security issues with the code you've written so far.
It's only a short section, but it's essential reading!
If you have things like textboxes and text areas on your forms, then you need to do some security
checking on the data that comes in. That's because of things like Cross-Site Scripting. This is
when somebody enters scripts into your textboxes to launch an attack on your site. Take this
simple form as an example:
<?PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$first_name = $_POST['first_name'];
echo $first_name;
?>
</head>
<BODY>
</BODY>
</html>
This form is one of the files you download. It can be found in the scripts folder and is called
testSecurity.php.
Load it up and you'll see that it's just a textbox and a Submit button. Click the button, and you
should see "test name" printed on the page.
Now, click inside the textbox and enter the following Javascript:
<SCRIPT>alert("Scary Script!")</SCRIPT>
Click the Submit button, and then watch what happens. You should see this (you need Javascript
enabled in your browser):
It's just an alert box. But it could have been something worse!
When you click Submit this time, you should see the following:
This time, a HTML hyperlink displays above a comments text area. If that was your forum,
guess where the link would be?
To stop this kind of thing happening, there are a number of techniques you can use. We'll explore
them in the next few parts.
You can use the inbuilt PHP function htmlspecialchars( ) to convert certain HTML into their
respective symbols. (See the previous lesson for why you want to do this.) For example, take the
following HTML tag:
<B>Bold text</B>
On a web page, that just gives you Bold text. If you enter it into a textbox, and don't convert,
then the browser renders it as HTML – in other words, it gives you bold text. The same is true of
this:
This unconverted HTML will turn into an hyperlink. That's because things like left and right
pointy brackets are considered to be HTML. The browser sees the code above, and turns it into a
hyperlink. It DOESN'T display the left and right pointy brackets. If you actually wanted a left
point bracket on your page, you'd use the HTML special character for this symbol:
<
And this, essentially, is what the htmlspecialchars( ) function does – turns the HTML into the
special character codes.
As an example, change your PHP script from the previous lesson from this:
$first_name = $_POST['first_name'];
echo $first_name;
to this:
$first_name = $_POST['first_name'];
$first_name = htmlspecialchars( $first_name );
echo $first_name;
Run your code again, and see what happens. You should see this display in the browser:
$first_name = htmlspecialchars($first_name);
So in between the round brackets of htmlspecialchars( ) you type the name of the variable you
want to convert to special characters. PHP takes care of the rest.
htmlentities( )
A function similar to htmlspecialchars( ) is htmlentities( ). Instead of the above, you can do this:
$first_name = $_POST['first_name'];
$first_name = htmlentities( $first_name );
echo $first_name;
The difference between the two is that htmlentities( ) will check for non-English language
characters, such as French accents, the German umlaut, etc. So if you think your attacker might
launch an attack in a language that is not English, then use this.
In the next part, we'll see how to strip HTML tags altogether.
PHP strip_tags
A third security option for your HTML forms is to use the strip_tags( ) function. (See the
previous lessons for why you want to do this.) It will, as its name suggests, strip all HTML for
you. You can, however, tell this function to ignore HTML that you consider harmless, or that
you want to include. Here's the syntax:
$first_name = $_POST['first_name'];
$first_name = strip_tags( $first_name );
echo $first_name;
The new line is set up to strip all HTML from the variable called $first_name. When the script
is run, it will look like this:
As you can see, only the text of the HTML is left – A Nasty Site.
If it would be OK for people to enter things like bold text or italics, then you'd set up the function
like this:
$first_name = $_POST['first_name'];
$first_name = strip_tags( $first_name, "<B>" );
echo $first_name;
Summary
When you have text coming from a form, you should always use a security technique to thwart
an attack. However, it's naïve to think we can thwart every attack, and a determined and skilful
hacker could probably defeat you. But if you take sensible security measure, you should be able
to defend yourself against most attacks. It's well worth doing more research on the subject.
search Google for the phrase PHP Security.
In the next section, we'll take a look at opening and working with files in PHP.
The ability to open up files such as plain text or CSV files is a great asset for you as a
programmer. Not every job requires a database with multiple tables, and storing simple data in a
text file can be a good alternative. Especially if your web host doesn't allow you to have a
database!
In this section, we take a look at the various way you can manipulate files with PHP. We'll start
by opening a plain text file.
For this section, we'll be using the file called dictionary.txt, which is amongst the ones you
downloaded (in the scripts folder).
Open this file up, and take a look at the contents. It should look like this:
It's just a long list of values separated by an equals sign. On the left of the equals sign is an
abbreviation, and on the right its meaning. We'll open this text file with PHP code. You'll see
different ways to open up and work with this text file. Click below to make a start.
To open up a file, there are a few methods you can use. The one we'll start with is readfile( ). As
it's name suggest, it reads the contents of a file for you. Try this simple script (this assumes that
you've read the short introduction on the previous page).
<?PHP
?>
Save the script with any file name your like, but make sure it goes in the same folder as your
dictionary.txt file (see the previous page for an explanation of this file). Run your new code,
and see what happens.
You should get a web page full of text, with no separation and no line breaks.
And that's it! Simple, hey? Only two lines of code. You can even get it down to one line:
print readfile("dictionary.txt");
$file_contents = readfile("dictionary.txt");
You start by typing readfile, and then a pair of round brackets. In between the round brackets,
type the name of the file you want to open. This can be either direct text, as above, or a variable,
like this:
$file_to_read = "dictionary.txt";
print readfile($file_to_read);
You don't have to put the file you're trying to read in the same directory. If you had a folder
called files in your directory, you could do this:
$file_to_read = "files\dictionary.txt";
print readfile($file_to_read);
The readfile( ) function is useful if all you want to do is open up a file and read its contents.
file_get_contents(file_to_read);
Another function that just reads the contents of a file is file_get_contents( ). It is available in
PHP version 4.3 and above. Here's an example:
<?PHP
$file_to_read = "dictionary.txt";
print file_get_contents( $file_to_read );
?>
This used in more or less the same way as the readfile function. The difference for us is the
change of name to file_get_contents( ).
In the next part, we'll take a look at the more commonly used fopen function
A better method to open files is with fopen( ). This function gives you more options that, such as
setting whether the file is for reading only, for writing to as well, and a few more options. Here's
an example (this assumes that you've read the short introduction on the previous page):
<?PHP
?>
Run this script and see what happens. You should see something like the following printed out:
Resource id #2
The "r" on the end means "open this file for reading only". We'll see other options in a moment.
But now that you've told PHP to remember the location of the file you want to open, how do you
read the contents of the file?
One way is to use fgets( ). This will read a specified number of character on a single line of text.
It's typically used to loop round and read each line of text. In the example below, we're printing
out each line separately. When you're using fgets( ), you also need to check when the end of the
file has been reached. This is done with the inbuilt function feof - file, end of file. Try the script
out, then we'll explain what's happening:
<?PHP
while (!feof($file_handle)) {
$line_of_text = fgets($file_handle);
print $line_of_text . "<BR>";
fclose($file_handle);
?>
What you should find is that the contents are printed out on separate lines. But how does it work?
What we're doing here is asking PHP to open up a file, and remember the location. The location
is stored as a file handle. We're putting this into a variable called $file_handle. So we haven't yet
read the contents of the file – we've just asked PHP to remember where it is.
!feof( $file_handle )
A while loop, remember, just goes round and round until you tell it to stop. It goes round and
round while a condition is true. The condition between the round brackets was our strange !feof
line.
The function feof( ) means "file end of file". It tells PHP when the end of a file has been reached.
You put the file between the round brackets of the function:
feof( $file_handle )
This means, end of the file referred to in the variable called $file_handle. Except, we've used the
NOT operator ( ! ):
!feof( $file_handle )
That's because we want to keep looping while the end of the has NOT been reached:
This whole line, then, reads: "While the end of the file has NOT been reached, loop round the
file pointed to in $file_handle." As soon as the end of the file has been reached, the while loop
will end.
We're using the fgets( ) function to get a line of text from our file. Again, we need the file
handle:
fgets( $file_handle );
So we get a line of text from our file, and then place the line into a variable. We then print out
the line of text:
fclose( $file_handle );
All this does is to close the open file. It tells PHP that the pointer to the file is no longer needed.
You should always close files that you have opened with fopen().
The code is a bit tricky, when you're meeting it for the first time. But this kind of file opening is
useful when you need to read each line of text. With our file, for example, we could separate
each half of the line. We might want to put the abbreviations into one list box and the meanings
into another.
Another point to bear in mind about fgets is that it can take (and often does) a second argument –
the size of the line to read:
fgets($file_handle, line_size);
The line size needs to be in bytes. The default is 1024. But this line size is only optional in PHP
version 4.2 and above. If your version is earlier than this, then you may get an error if you miss
out the line size:
fgets($file_handle, 1024);
If you're really packing a lot of information into each line, then just increase the number for line
size.
In the next part, we'll see other options for fopen, rather than the "r" above.
In the code from the previous page, we used fopen and to get at our file. But we were only
reading the file. That's was why we had the letter "r" in the round brackets of fopen:
But there are other options. Here's a fuller list of things you can replace "r" with.
So if you wanted to read and write to the file, you'd use this:
If you need to work with binary files (like images), then you can add the "b":
It's a good idea to check if the file exists, before trying to do something with it. The file_exists( )
function can be used for this:
if ( file_exists( "dictionary2.txt" ) ) {
}
else {
In between the round brackets of file_exists( ) you then type name of your file. If it does exist,
then you can go ahead and do something with it; if not, you can write code to handle any errors.
In the next part, we'll see how to write to a file with PHP.
When you need to write to files, there are some more functions you can use.The first of these
we'll look at is the fwrite() function. (This needs fopen( ) to first to get a file handle.)
In the next script, we'll try to write some text to a file. We'll use the "w" option, as this will create
a file for us, if we don't have one with the filename chosen.
<?PHP
fwrite($file_handle, $file_contents);
fclose($file_handle);
print "file created and written to";
?>
The new line is the blue coloured one. First we ask PHP to open the file and create a file handle:
So we're asking PHP to create a file handle that points to a text file called "testFile.txt". If a file
of this name can't be found, then one will be created with this name. After a comma, we've typed
"w". This tells PHP that the file will be write only.
In between the round brackets of fwrite( ), we've placed two things: the file we want to write to,
and the contents of the file. And, except for closing the file, that's all you need!
To test to see if it works, run the script. Then look in the folder where you saved the script to.
There should now be a file called testFile.txt.
Exercise
Change the "a" into "r". Run your script again, then open the text file. What did you notice? Did
the contents of the text file change?
file_put_contents( )
In the next part, you'll see how to work with CSV files (comma delimited files).
CSV is a type of file. It means Comma Separated Values. Spreadsheets software like Excel will
offer you the opportunity to save files with the CSV extension. We'll see how to work with these
types of files now.
The image below shows an Excel spreadsheets. It's just a simple price list:
The next image shows the spreadsheet being saved as a CSV file:
The above CSV file is the one we want to work with. It shows each line separated by commas.
PHP has a function that allows you to work with CSV file. It's called fgetcsv( ). It's just like the
fgets function you used earlier. The difference is that fgetcsv( ) separates each line on the
commas, and puts each part into an array. Before trying the next code, make sure you copy the
widgets.csv file, from the ones you downloaded, over to the same folder where your script is.
The widgets.csv file is in the scripts folder. Here's the code:
while (!feof($file_handle) ) {
fclose($file_handle);
?>
When you run the script, you should see all the lines of text printed out. (You may have a
question mark in place of the currency symbol, though.) Here's how it works.
The first two lines you've already met: get a handle to the file you want to open, then create a
while loop to loop round it.
while ( !feof($file_handle) ) {
In between the round brackets of fgetcsv, we've typed to things: our file handle, and the size of
the line to read. The size, in this case, is 1024 - 1 kilobyte. You can change this value. When the
function gets the line of text, it puts it into the variable we've called $line_of_text.
But $line_of_text will now be an array. Each line of our text file looks like this:
The fgetcsv function will split this line when it sees the comma. It then creates a position in the
array to hold each part of the line. So it will set up an array with three positions, in our case.
Those positions will be as follows:
All we're doing here is to print out what is in each position of the array. We've then added a
HTML line break, just for display purposes.
If you have CSV files from a spreadsheet that you need to display on a web page, the fgetcsv
function can come in quite handy!
In the next part, you'll see other options for reading a text file line by line
There are a few inbuilt PHP functions you can use to find out file paths. This is useful for finding
the exact location (relative or absolute) of your scripts or pages. Here's a few example. Before
you try these out, create a new PHP page and save it as fileDir.php.
<?PHP
$absolute_path = realpath("fileDir.php");
?>
<?PHP
$dir = dirname("folder/myphp/fileDir.php");
?>
To get the names of the folders, you can use the dirname( ) function. This will strip off the name
of the file and return the rest of the text between the round brackets of the function.
<?PHP
$bas = basename("folder/myphp/fileDir.php");
?>
If you only need to get at the name of the file, then use the basename( ) function. When you type
a longer file path in between the round brackets of the function, it will strip off the rest and leave
the name of the file.
Final Note
Careful when allowing users to upload files from external sources. This could be used to attack
your site. There are a few security implications when working with files.
<?PHP
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode('=', $line_of_text);
fclose($file_handle);
?>
The lines to examine are in blue; the rest you have met before (get a file handle, loop round, use
fgets to read the line). The first line to note is this:
If you remember the string section, you'll also be familiar with the explode function. It splits a
line of text, based on whatever you have provided for the separator. In our code, we have used
the equals sign ( = ) as a separator. This is because each line in the dictionary.txt file looks like
this:
When the explode function is executed, the variable called $parts will be an array. In our text
file there will only be two positions in the array, one for each half of the equals sign.
So $parts[0] will hold the abbreviation (AAS) and $parts[1] will hold the meaning.
The next time round the while loop, the second line will be read from the text file. Exactly the
same thing happens, so the line will be split again, and placed into an array. This is a good
technique to use, if you want to split each line and do something different with each part of the
line.
In the next part, we'll take a look at File Locations, and how to work with them.
Knowing how to handle date and time values in PHP will be a useful addition to your
programming skills. In this and the following sections, we'll take a look at how to process this
type of data.
The inbuilt PHP function date( ) is the most widely used method of returning date values.
Unfortunately, there is a very long list of things you can put between the round brackets of the
function! Try this script, to get an idea of how it works:
<?php
$today = date('d-m-y');
print $today;
?>
It should print the day of the week first (d), then the month (m), then the year (y). But this will be
the numerical format. So it will print something like:
04-07-2006
This type of date can be very confusing, however, because it means the 7th of April in the USA.
In the UK, it means the 4th of July.
But to use the function, you first type date followed by the round brackets. In between the round
brackets you can type a whole host of different date combinations. There's a list coming up. But
take note of the case. Change your script to capital letters and watch what happens.
Also, the separator can be anything you like (within reason). So you can have this instead of a
hyphen:
$today = date('d:m:y');
Or this:
Or even this:
$today = date('d~m~y');
Note the single quote marks surrounding the date text. Miss these out and you'll get errors. You
can use double quotes, but singles are recommended: dates can be a bit quirky.
Click the next part for a fuller list of the date and time characters to use between the round
brackets of date.
The following is some lists of the date and time characters to use between the round brackets of
date. They are all case sensitive. The date function syntax is this, remember:
date( date_characters_here )
<?php
$today = date('d-m-y');
print $today;
?>
The first list is for the day of the week characters. Try them out on your script above.
That's quite a lot of characters! Mostly, you'll be dipping in and out to find the one you need.
Here's a few examples of the way you can use the above. Try out the following scripts to see how
they work.
<?PHP
?>
<?PHP
$today = date('W');
$year = date('Y');
print "It's week " . $today . " of " . $year;
?>
<?PHP
?>
<?PHP
?>
Another useful date/time function is getdate. This will return an array (associative) with all the
date and time values. You can use it for things like comparing one date to another. For example,
comparing how many days have passed since a given date. Here's the syntax:
getdate( time_stamp );
The time stamp is optional. If you leave it out, it gets the values for the current local date and
time. The parts of the array are this:
seconds
minutes
hours
mday (day of the month as a number)
wday (day of the week as a number)
mon (month a number)
year
yday (year day as a number)
weekday (day in text format)
month (month in text format)
0 (Seconds since the Unix Epoch)
Because getdate returns an associative array, you can just do this sort of thing:
$today = getdate();
print $today['mday'];
print $today['wday'];
print $today['yday'];
So whichever part of the array you want to access goes between square brackets. You then type
one of the above Keys between quote marks.
As a further example, suppose you want to work out how many days it's been since a forum
member last posted something. And that you have used this to write the date of the last post in a
database:
$post_date = date('z');
Now, you've read this value back in, and you want to compare that date against today's date. You
can do it like this:
<?PHP
$post_date = 60;
$today = getdate();
?>
$today = getdate();
We've then used "yday" to calculate how many days have elapsed since the last post:
Working with dates and times can be quite tricky, and a good reference is the PHP.net website.
As well as setting out all the date and time functions, there's lots of posts from people with good
date/time scripts:
http://uk.php.net/manual/en/function.date.php
PHP has the ability to connect to and manipulate databases. The most popular database system
that is used with PHP is called MySQL. This is a free database system, and comes with the
Wampserver software you may have installed at the start of the course. We will be working with
MySQL databases throughout these lessons.
Another way to bring up phpMyAdmin is to simply type the following address in your browser:
http://localhost/phpMyAdmin/
You should see the phpMyAdmin page display. This one, in earlier versions:
If you need to set a password for phpMyAdmin, click the link at the top that says "Change
password". (You should do this if your webserver is connected to the internet and the outside
world will have access to it. We are doing all our coding on a local machine, so can leave the
username and password on their defaults of root and blank. We'll change it in a later tutorial,
though.)
We're going to be creating databases using this. But if you can see the page OK, then you have
everything you need. You might want to bookmark the mysql page, though!
If you can't see the page, then either MySQL isn't installed, or it's not configured correctly.
Again, you need to refer to the documentation to fix this.
However, we have a few databases amongst the files you downloaded. So you can still follow
along with the later tutorials.
In the next part, you'll see how to create a database with phpMyAdmin.
You can create all of your database tables and queries using PHP code. But before doing that, it's
a good idea to get an understanding of just what it is you'll be creating. If you're new to the world
of databases, then here's a simple primer.
A database is a way to store lots of information. You might want to store the names and
addresses of all your contacts, or save usernames and passwords for your online forum. Or
maybe customer information.
In a database, you save the information in a Table. A single database can contain many tables,
and they can be linked together. When the tables are linked together, it's said to be a relational
database. If you just have a single table in your database, then it's called a flat-file database. Flat-
file database are easier to create and understand, so we'll start by creating one of these using
phpMyAdmin.
So start your server and bring up phpMyAdmin, if you havaen't already. Log in with your
username and password (the password is blank, if you haven't changed anything.)
Although it looks a bit muddled, the part to concentrate on is the textbox under the words create
new database, as in the next image:
If you can't see a section "Create new database", click New on the left-hand side of
phpMyAdmin:
After you have typed a name for your new database, click the "Create" button. You will be taken
to a new area. This, in older versions:
In this new area, you can create a Table to go in your database. At the moment, as it says, there
are No tables found in the database. But the database itself has been created.
To create a new table, type a name for it in the box at the bottom. You can also type a number for
the Fields textbox. The fields are the columns, remember, and will be things like first_name,
When you've finished, click the Go button. Another, more complex, area will appear:
In this new area, you set up the fields in your database. You can specify whether a field is for
text, for numbers, for yes/no values, etc. We'll see how to do that in the next part.
You have four Fields in your table from the previous section. Although they are set out in rows
in the images, the rows are actually the Columns you saw earlier – the Fields. Each Field needs a
name. So go ahead and type the following for your Field names:
In later versions of phpMyAdmin, Field will say Name, and the default types will be INT:
So we have given each column in our table a name: ID, First_Name, Surname, and Address.
The next thing to set is what type of data will be going in to each field - do you want to store text
in this field, numbers, Yes/No value, etc?
ID – A number, used just to identify each record. This needs to be unique for each record
First_Name – Text
Surname – Text
Address – Text
If you look at the list of field types, there is an INT but no Number; and there are four different
Text Types to choose from. We can use INT (meaning integer) for the numbers, but again, there
are a few Integer Types to choose from. And that's leaving out things like float and double.
Here's the difference between them, though.
Integer Values
The signed and unsigned are for minus and non minus values. So if you need to store negative
values, you need to be aware of the signed ranges. If you were using a TINYINT value, for
example, you can go from minus 128 to positive 127. If you didn't need the minus value, you can
go from 0 to positive 255.
For our address book, we have an ID field. We're using this just to identify a record (row). Each
record will be unique, so it will need a different number for each. We can set it to one of the INT
values. But which one?
If we set ID to TINYINT, then you'd run in to problem if you tried to store more than 255
records. If you used SMALLINT, you'd have problems if you tried to stored the details of friend
number 65536. IF you have more than 65 and half thousand friends, then you need a different
INT type. We'll assume that you don't, so we'll use SMALLINT.
The length for the text types can be quite confusing. The MySQL manual says this about the
various lengths that each text type can hold:
This in not terribly helpful for beginners! So what does it mean. Well, the L + 1 part means, "The
length of the string, plus 1 byte to store the value." The translated values for each are
approximately:
To confuse the issue even more, you can also use CHAR and VARCHAR to store your text.
These are quite useful, if you know how many characters you want to store. For example, for a
UK postcode you don't need more than 9 characters, and one of those will be a blank space. So
there's no sense in setting a postcode field to hold 4 gigabytes! Instead, use CHAR or
VARCHAR.
CHAR
You specify how many characters you want the field to hold. The maximum value is 255. For
example:
CHAR(10)
This field can then hold a maximum of ten characters. But if you only use 4 of them, the rest of
the 10 characters will be blank spaces. The blank spaces get added to the right of your text:
"TENLETTERS"
Like CHAR, but the rest of the characters are not padded with blank spaces. The maximum value
before MySQL 5.0.3 was 255. After this it's jumped to 65, 535. With VARCHAR, there is also
an extra byte that records how long your text is.
ID SMALLINT
First_Name VARCHAR
Surname VARCHAR
Address TINYTEXT
We've only set Lengths for the VARCHAR TYPES. If you leave it blank for VARCHAR, you'll
get a default value of 1 character (you may even get errors, in later versions of phpMyAdmin).
Null
This is an important field in database terminology. It essentially means, "Should the field contain
anything?" If you set a field to NOT NULL, then you can't leave it blank when you come to
adding records to your database. Otherwise you'll get errors.
Default
Do you want to add anything to the field, just in case it's left blank when adding a record? If so,
type it in here.
The three icons above (earlier versions only) are Primary Key, Index, and Unique. Primary keys
are not terribly important for flat-file databases like ours. But they are important when you have
more than one table, and want to link information. They are set to unique values, like our ID
field. An index is useful for sorting information in your tables, as they speed things up. Unique is
useful for those fields when there can't be any duplicate values.
To set up an Auto Increment field in later versions of phpMyAdmin, put a check in the box for
A_I. From the dropdown list under Index, select Primary:
Your field screen then, minus the parts we've ignored, should look like this (CHAR should be
VARCHAR, in the image below):
Now click the Save button in the bottom right. (If you get a #1067 error in later versions of
phpMyAdmin, change the Default dropdown list from TimeStamp to None.). You'll be taken
back to the Structure screen. There should be a lot more information there now. Don't worry if it
looks a bit confusing. All we want to do is to add one record to the table. We'll then use PHP
code to add some more.
But bear in mind what we've done here: we've just set up the fields for our table, and specified
the kind of information that will be going into each field (the columns). We haven't yet added
any information to the table.
In the next part, you'll learn how to add a record to your database table.
When you click on Insert, you'll be taken to a new area. This one:
As you can see, our four fields are there: ID, First_Name, Surname, and Address. But look at the
lengths of the textboxes under the Value. The sizes are determined by the length of the Fields.
The address area is a lot bigger, because we used TINYTEXT.
ID: 1
First_Name: Test
Surname: Name
Address: 12 Test Street
Finally, click the Go button at the bottom of the screen to create the Row in your table. You will
be returned to the Structure screen.
And that's it - you now have a database to work with. To see where it has been saved, navigate to
your PHP folder on your hard drive. Double click the folder called mysql. Inside this folder will
be one called data. This is where all of your databases are stored:
If you have PHP web space, you can upload this folder and its contents to your data folder, and
you should then be able to access the tables in the database with PHP code.
We can move on to doing just that - accessing this database with some PHP code.
In this section, you'll see how to manipulate the simple Address Book database you've just
created. Using PHP code, you'll first open the database. Once the database is open, you can then
read its contents. You'll also need to know how to add new records, and delete records. First,
though, a database has to be opened, before you can do anything with it.
The first job is to actually connect to MySQL. As it's name suggests, mysqli_connect( ) does
exactly that. Here's the code we're going to be using. But this is just to get your started. It is
recommended that you don't dash off and use this on the internet! This is for learning purposes
only. We'll use a different way to connect, shortly.
<?PHP
$user_name = "root";
$password = "";
$database = "addressbook";
$server = "127.0.0.1";
?>
Save your work and try it out on your server (this assumes that you have the Address Book
database we created earlier, and that it is in the data folder of MySQL.
The first four lines are just setting up variables, and putting something in them:
$user_name = "root";
$password = "";
$database = "addressbook";
$server = "127.0.0.1";
Page 177 of 251
The username we're trying here is "root" and the password is blank. These are the MySQL
defaults. You don't need to change these, in most cases. (This is purely for testing on a local
machine. You do need to change the MySQL defaults if you're running your own server
connected to the internet.)
Hopefully, you won't have any errors. But the line that connects to MySQL is this:
So you type the name of the function first ( mysqli_connect ), followed by the round brackets. In
between the round brackets, you need three things: the name of your server, your MySQL
username, and your MySQL password. These can be entered directly, like this:
$user_name = "root";
$password = "";
$server = "127.0.0.1";
Try it yourself and you should see the message "Connection to the Server opened" printed out.
There is, however, a problem with this - your username and password details are being typed in
plain text in the PHP file. That means a hacker could gain access to this file and read your
details.
What'll do instead is to place this sensitive information in a separate file, and use the PHP inbuilt
functions require and define.
The inbuilt PHP function define is used to set up constants. Here's an example:
define('NAME_OF_CAT', 'Tiddles');
In between the round brackets of define you first need the name of your constant,
NAME_OF_CAT, in the code above. After a comma, you type the value that you want to place
in your constant. Now you can do things like:
if (NAME_OF_CAT == 'Bob') {
define('NAME-OF-CAT', 'Tiddles');
The error is because you can't use hyphens in your constant names.
So, instead of hard-coding a user name and password in every PHP file, we can define them in a
separate file.
By default, the password is normally blank. But you can (and should) set up a password here.
Click the GO button to see the following screen:
But that's why define for us says password, and not left as a blank string:
define('DB_PASS', 'password');
Change password to whatever you typed as your password in the phpMyAdmin screen above.
Now that you have set up some constants, it's time to save the file. It's highly recommended that
you don't save your sensitive information in the root folder of your server. This is usually the
www folder, if you have some webspace on the internet. Save the file outside of the www folder,
one folder up should be OK. That way, hackers will find it very difficult to gain access to it. In
the image below, you can see the www folder, and the configure.php file:
The require keyword in PHP is similar to include, in that it is used to include another file in your
code. The difference is that require will halt the script when it detects an error and give you an
E_COMPILE_ERROR warning. If you use include then the script will continue to execute and
just give you an E_WARNING error. You use it like this:
<?PHP
require 'somefile.php';
?>
It's better to put require right at the top, without any blank lines after <?PHP. The blank lines can
sometimes generate an error that can drive you crazy trying to solve.
<?PHP
require '../configure.php';
?>
Notice the require line has no round brackets. So we haven't done this:
require('../configure.php');
Another thing to note is the two dots and a slash at the start. (We've used a forward slash, here,
but try a backslash, if you're getting error messages.) The two dots and a slash mean "To find the
file, go up one directory from where you are".
Because we've defined our constants in a separate configure file, we can use these between the
round brackets of mysqli_connect:
Doing things this way means that we're not hard-coding our details into the PHP connection file.
Also, we don't have to keep typing our login details every time we want to connect to the server -
just use require at the top of the code instead.
$database = "addressbook";
We now need to do something with this variable. So add this new line to your code (the new line
is in blue text):
<?PHP
require '../configure.php';
$database = "addressbook";
if ($db_found) {
?>
We now have mysqli_connect on the right of an equal sign. To the left, we have a new variable,
which we have called db_handle. This variable will store a connection to the server.
You use the mysqli_select_db( ) function to specify which database you want to open. The
function then returns a true/false value. If it finds your database, a value of true is returned; if
your database can't be found then a value of false is returned. In between round brackets, you
need a connection to the server (db_handle, for us) as well as the database you want to connect
to. We've used an if statement to check the value of $db_found. A suitable message is printed,
depending on whether the database was found or not. (The two print lines are only for testing
purposes.)
$database = "addressbook";
$database = "addressbook2";
Run your code again, and you should see Database NOT Found printed out (unless you have a
database called addressbook2). Change the database name back to addressbook.
Now that we've connected to MySQL, and connected to a database, it's time to close the
connection.
Closing a connection to a database is quite easy. If you've used a file handle, as above, you just
do this:
mysqli_close( $db_handle );
Otherwise, you don't need to bother. It's recommended that you take the file handle approach,
though. Place the close code in the if statement, right after "Database found".
Now that we've got a connection to the database, it's time to look at how you can access the data
in the database. We'll do that in the next part.
To read records from a database, the technique is usually to loop round and find the ones you
want. To specify which records you want, you use something called SQL. This stands for
Structured Query Language. This is a natural, non-coding language that uses words like
SELECT and WHERE. At it's simplest level, it's fairly straightforward. But the more complex
the database, the more trickier the SQL is. We'll start with something simple though.
What we want to do, now that we have a connection to our database, is to read all the records
from our address book, and print them out to the page. Here's some new code, added to the PHP
script you already have. The new lines are in blue:
<?PHP
require '../configure.php'
$database = "addressbook";
if ($db_found) {
}
else {
mysqli_close($db_handle);
?>
Before we go through the new code to see what's happening, run your script. You should find
that the address you added in a previous section is printed out. (We only have one record at the
moment.)
1
Test
Name
12 Test Street
The $SQL is just a normal variable. But we're putting into it a long string. This is a SQL
statement. Here's a brief run down on SQL.
SQL (pronounced SEEKwel), is a way to query and manipulate databases. The basics are quite
easy to learn. If you want to grab all of the records from a table in a database, you use the
SELECT word. Like this:
But your SQL statements are easier to read if you type the keywords in uppercase letters. The
keywords in the lines above are SELECT and FROM. The asterisk (*) means "All Records".
Table_Name is the name of a table in your database. So the whole line reads:
You don’t have to select all the records from your database. You can just select the columns that
you need. For example, if we wanted to select just the first name and surname columns from this
table, we can specify that in our SQL String:
When this SQL statement is executed, only the First_Name and Surname columns from the
database will be returned.
There are a lot more SQL commands to get used to, and you'll meet more of them as you go
along. For now, we're just selecting all the records from our table.
mysqli_query( )
The mysqli_query( ) function is used to send a SQL query to your database. If you have typed
out your SQL correctly, then the function will return a value. This value will be true, false, or a
file handle. Because we're using the SELECT keyword, the value returned by will be a file
handle. In our code, the line was this:
The file handle returned in our $result variable just points to the results. It doesn't actually bring
anything back. To bring back the data, we had this inside a while loop:
mysqli_fetch_assoc( $result )
The assoc part means Associative. As in "associative array". So we're asking that the results be
brought back in an array format. In between the round brackets of mysqli_fetch_assoc we have
typed the name of our file handle – the one that was pointing to the results of SQL statement.
Remember: an associative array is one where the keys are text. So it's this format:
Array['One'] =
Array['Two'] =
Array['Three]' =
Array[1] =
Array[2] =
Array[3] =
When the mysql_fetch_assoc function returns an array, we're putting it all into a variable called
$db_field. The Key part of the array is all the Column names from our database tables. This is
done automatically for you. So the array format will be this:
$db_field[Column_Name] = Value
The reason why you're doing this is so that you can loop round the array and access the values
from the table. Here's our loop, without anything between the round brackets:
while ( ) {
Array_Name[Table_Coulmn_Name] = Value_From_Record
Because that is a bit complex, let's go through the steps we've used to access the records from our
table:
1. Set up a SQL Statement that can be used to get the records from the database table
2. Use mysqli_query() to bring back the records we've specified in Step 1
3. Use mysqli_fetch_assoc() to set up an array. The array will contain all the records that were
returned in Step 2
4. Loop round all the data in the array using a While loop
$result = mysqli_query($SQL);
$db_field = mysqli_fetch_assoc($result)
To add records to a table in your database, you use more or less the same code as previously. The
only thing that needs to change is your SQL statement. The steps we're going to be taking are
these:
In our previous script, we used some SQL to grab records from our Address Book database table.
We then used a While loop to print all the records out. Because we're now going to be adding
records to the Address Book table, we need some different SQL. Here's the script. The new line
is in blue (The double and single quotes need to be entered exactly, otherwise you'll get errors
when you run the code):
<?PHP
require '../configure.php'
$database = "addressbook";
if ($db_found) {
}
else {
?>
You met all of this code from the previous section. The only difference is the new SQL
statement! What the code does is to set up some variables, open a connection to the database, and
then execute the SQL query. Let's have a look at the new, and rather long, statement.
To add records to your database, you can use the INSERT statement. There are plenty of ways
to use this statement, but we'll stick with something simple: adding
new values to all of our table columns.
You start by typing the words "INSERT INTO". This can be in any case you like: upper, lower
or a mix. It's easier for you to read if it's in uppercase letters.
The next thing you need is the name of a table to insert your new values into. For us, this is the
table that we've called tbl_address_book.
Following the name of your table, type a pair of round brackets. Inside the round brackets, you
can type the names of the columns in your table:
Notice how we haven't included the ID column from our table. That's because the ID column was
the one we set up to be an auto-incrementing number. We don't need to worry about this column
because MySQL will take care of adding 1 to this field for us.
Now that you've specified which table you want to insert values into, and specified your column
names, you can add the values you want to insert.
To add values, you type the word "VALUES" after the round brackets of your column names:
Notice how we've surrounded all of our text with double quotes. But inside of the round brackets
of VALUES, we've used single quotes.
But try your code out now, and see if it's all working properly. You should find that you now
have two records in your database table.
Exercise
Replace the values 'Paul', 'McCartney', and 'Penny Lane' with values of your own. Run your
script again to add your new record to the database. Now run your other script to read the values
back out.
In the next part, you'll learn how to import a database into phpMySQL. You'll need this database
for the lesson on Prepared Statements..
To add records to a table in your database, you use more or less the same code as previously. The
only thing that needs to change is your SQL statement. The steps we're going to be taking are
these:
In our previous script, we used some SQL to grab records from our Address Book database table.
We then used a While loop to print all the records out. Because we're now going to be adding
records to the Address Book table, we need some different SQL. Here's the script. The new line
is in blue (The double and single quotes need to be entered exactly, otherwise you'll get errors
when you run the code):
<?PHP
require '../configure.php'
$database = "addressbook";
if ($db_found) {
mysqli_close($db_handle);
}
else {
?>
You met all of this code from the previous section. The only difference is the new SQL
statement! What the code does is to set up some variables, open a connection to the database, and
then execute the SQL query. Let's have a look at the new, and rather long, statement.
To add records to your database, you can use the INSERT statement. There are plenty of ways
to use this statement, but we'll stick with something simple: adding
new values to all of our table columns.
You start by typing the words "INSERT INTO". This can be in any case you like: upper, lower
or a mix. It's easier for you to read if it's in uppercase letters.
The next thing you need is the name of a table to insert your new values into. For us, this is the
table that we've called tbl_address_book.
Following the name of your table, type a pair of round brackets. Inside the round brackets, you
can type the names of the columns in your table:
Notice how we haven't included the ID column from our table. That's because the ID column was
the one we set up to be an auto-incrementing number. We don't need to worry about this column
because MySQL will take care of adding 1 to this field for us.
Now that you've specified which table you want to insert values into, and specified your column
names, you can add the values you want to insert.
To add values, you type the word "VALUES" after the round brackets of your column names:
After the word "VALUES", you type another pair of round brackets. Inside of these brackets,
you can type your values. Each value should be separated by a comma. You can use either direct
text, like we've done, or variables. You can even get these values straight from your HTML
form, which we'll see how to do later.
Notice how we've surrounded all of our text with double quotes. But inside of the round brackets
of VALUES, we've used single quotes.
But try your code out now, and see if it's all working properly. You should find that you now
have two records in your database table.
Exercise
Replace the values 'Paul', 'McCartney', and 'Penny Lane' with values of your own. Run your
script again to add your new record to the database. Now run your other script to read the values
back out.
In the next part, you'll learn how to import a database into phpMySQL. You'll need this database
for the lesson on Prepared Statements..
On the Import screen, click the Browse button at the top (Make sure that the Format dropdown
list at the bottom says SQL):
Click on the Structure tab at the top to see how we have set this database table up:
So we have four fields in the table: ID, username, password, and email. The Types for these
fields are tinyint, and varchar(20). The primary key is the ID field, which is also set up to be
Auto Incremented.
In the next part, you'll learn about something called Prepared Statements. You'll need your
membertest database for this.
However, the above SQL uses hard-coded values ('Paul', 'McCartney', 'Penny Lane'). What
usually happens, though, is that you have textboxes where people can enter details. When a
button is clicked these VALUES are then used in a SQL statement to add a new record. Before
we insert a new record, though, we'll explain Prepared Statements.
So far, we've used SQL that pulled all the records from a database, or SQL that inserted hard-
coded values like 'Paul' and 'McCartney'. More often than not, however, this is not what you
want to do. What usually happens is that you have textboxes where people can enter details, like
usernames, passwords, and email addresses. You then get these values from a HTML Form and
do something with them. In this lesson, you'll see how to pull records from a database based on
an email typed into a textbox. For this, we'll use something called a Prepared Statement.
Prepared Statements
When you ask users to enter details into a textbox and click a button, you are opening your
database up to attacks, especially from something called a SQL Injection attack. For example,
take this SQL Statement:
Here, we're selecting all the records from a database table called members. The SQL this time
has a WHERE clause added. The WHERE clause is used when you want to limit the results to
only records that you need. After the word "WHERE", you type a column name from your
database (email, in our case). You then have an equals sign, followed by the value you want to
When an email address is entered in the text box on our form, this value goes straight into the
variable without any checks. An attacker could type something else into the textbox, trying to
manipulate your SQL statement. They could add a DELETE part to delete records from your
database, or a DROP clause to delete the entire database itself. There are lots of ways an attacker
could inject SQL into your code. So you need to defend yourself against attacks.
To prevent SQL Injection attacks like these, you can use a Prepared Statement. Let's see how
they work.
Along with the database folder amongst the files you downloaded, there is a PHP script called
testPrep.php (in the scripts folder). We'll use this script, and the database, to teach you about
prepared statements.
Open up the testPrep.php file and you'll see some PHP at the top and a FORM in the BODY
section of the HTML. The form is just this:
email address <INPUT TYPE = 'TEXT' Name ='email' value="<?PHP print $email ; ?>">
</FORM>
It's a simple form, with a textbox and a button. The textbox is for an email address. When a
correct email address is entered, we'll print out a row from the database. The row contains an ID
number, a username, a password, and the email address. So we're querying the database table to
see if the email address entered into the textbox matches an email address from the table.
In fact, test it out. Load up the testPrep.php into your web browser. Enter the following email
address into the textbox:
test1@test1.com
Now click the button. If you're connected to your server, you should the following printed out:
1
test1
(If you're getting database errors, make sure you have your configure.php file in the right place,
as explained in a previous section.)
So the ID from the returned row is 1, the username and password are both test1, and the email
address is test1@test1.com. Now let's look at the PHP code.
<?PHP
$email = "";
if (isset($_POST['Submit1'])) {
require '../configure.php';
$email = $_POST['email'];
$database = "membertest";
$db_found = new mysqli(DB_SERVER, DB_USER, DB_PASS, $database );
if ($db_found) {
$result = $SQL->get_result();
if ($result->num_rows > 0) {
}
else {
}
else {
?>
$email = $_POST['email'];
This just get the text from the textbox on the form. But notice that we're not doing any error
checking here to see if it is a valid email address, or that the user hasn't entered anything
malicious. (You can do error checking here, if you want. But we'll keep it simple so as not to
overcomplicate the code. We're going to be using a prepared statement, so any malicious SQL
that has been added will get converted into a string, not a SQL statement.)
The next few lines set up the database username and password, as well as the server and database
name. Then we have this line:
This is a new way to connect to the database and server. Previously we used two steps:
mysqli_connect, and mysqli_select. Now, we're just using one step: mysqli. In between the
round brackets of mysqli, we have four things: the server name, the username, the password, and
the name of the database. (The first three are coming from the required file, configure.php. You
saw how to set this up in a previous lesson.) Notice the new keyword after the equal sign. You
need this to set up a new database object.
This is the first line of our prepared statement. We're preparing the SQL that we want to execute
on the database table. To the right of an equal sign, we have the name of our database object,
$db_found. Because it's an object you need two symbols without any space between them: a
dash (-) and greater than symbol (>). Next comes the inbuilt function prepare. In between the
round brackets of prepare, you need to type your SQL. We're selecting all the records WHERE a
certain condition is met. The curious bit is this:
The question mark is a placeholder, often called a parameter. The email part is the name of a
field in our database table. The placeholder, that ?, is going to be replaced with an actual value.
We do this on the next line:
$SQL->bind_param('s', $email);
Notice that the $SQL variable is now an object, which is why it has the -> symbols after it. Then
we have an inbuilt function called bind_param. As its name suggests, this is used to bind values
to those parameters you set up in the prepare function. Between the round brackets of
bind_param we have a single letter s surrounded by single quotes. After a comma goes the
value you want to bind, in our case this is the value we got from the textbox on the form - the
email address. (The variable name doesn't have to match the field name in your database.)
You can bind to more than one value. You may, for example want to check a username as well
as the email address. In which case, your prepare function might look like this:
Notice we have an AND part separating the two fields email and username. Each field has its
own equal sign and question mark placeholder
We have two letter s's now, one for each of the parameters. The $email and $user would be
variables that we get from the HTML form.
The 's' is short for string. You may have fields in your database that are numerical, in which case
you need and i (for Integer) or d (for double):
$SQL->bind_param('i', $some_integer_value);
$SQL->bind_param('d', $some_double_value);
$SQL->bind_param('b', $some_blob_value);
Once you have bound your parameters, you can go ahead and execute:
$SQL->execute();
The inbuilt function now is get_result. This will return an array of rows from your table.
if ($result->num_rows > 0) {
}
Here, we use the inbuilt function num_rows. We're testing to see if it's greater than zero. If it is,
we have this:
We're using a while loop to loop round the returned array. The array can be traversed with:
$db_field = $result->fetch_assoc()
The $db_field is just a variable name. You can call it almost anything you like. But $result-
>fetch_assoc( ) places each row from your database in the variable. You can then do something
with each row:
In the next tutorial, you'll see how to insert and update records using a prepared statement.
You can use prepared statements to insert a new record. Connect to the server and database with
mysqli:
Here, we're using the prepare function again. In between the round brackets of prepare, there's
this:
You use INSERT INTO when you want to add a new record to your database table. After the
name of your table you type the name of the table fields. In the code above, we have three fields:
username, password, and email. The fields go between round brackets. After a space, type
VALUES. For the round brackets of VALUES, we have three placeholder question marks (?),
one for each of the values that will go into the fields.
Notice that there are three letters s's, as each of the fields in the table hold string values. We then
have three variables: $uName, $passW, $email. These can come from a HTML form.
$SQL->execute();
To get a look at all this in action, there is some code in your scripts folder. Have a look at the file
called testPrep2.php. Then test it out on your server. Enter some values in the textboxes and
you should the message "New row inserted" printed out.
You update a record in PHP and MySql pretty much the same way you insert a new record.
Here's some code that updates a username and password, based on an email address entered into
a textbox.
We still use the prepare function. This time between the round brackets we have this:
The SQL keywords are UPDATE and SET. We're updating the members database table. We're
setting the username and password, each of these with its own question mark placeholder. The
WHERE clause at the end is used for the email address. So, "UPDATE the username and
password WHERE the email address matches the one provided.
Notice that the bind_param function needs three letter s's, one for each of the string fields in the
table:
Again, $uName, $passW, and $email are all variables we get from a HTML form. These values
will replace the question mark placeholders in the prepare function.
$SQL->execute();
The full code to update a MySQL record can be found in testPrep3.php, which is one of the
files you downloaded (in the scripts folder).
If you want to delete records, the same principle applies: set up a connection to server and
database, then prepare a SQL statement:
$SQL->bind_param('s', $email);
This binds a string to the email question mark from the WHERE clause. The actual string is
coming from the $email variable.
$SQL->execute();
The full code to delete a MySQL record can be found in testPrep4.php, which is one of the files
you downloaded (in the scripts folder).
A lot of sites add a members section, where users are authenticated by means of a username and
password. Once the user is logged in successfully, he or she can then gain access to the restricted
areas of the site. You'll see how to do that in this walkthrough.
For the walkthrough, there are some scripts already prepared. These can be found in the login
folder, which is one of the folders you downloaded. (It's in the scripts folder.)
In this walkthrough, we'll explore some of the things you need to bear in mind when creating a
username/password section on your site. What we don't offer is a complete login script. This is,
after all, a tutorial site, and we'd much rather help you develop your own scripts.
The database we've set up for these tutorials is as simple as they come. It consists of a table
called login, with three fields: an ID field, a field for the username (called L1), and a field for
the password (called L2). We're using a simple table, so as not to complicate the tutorials. But
you'll want to add more fields, when you come to implement your own login pages. For example,
you may want an email address field so that you can send a new member a message about
successful registration, and a timestamp field so you know when the user signed up.
This lesson is part of an ongoing User Authentication tutorial. The first part is here: User
Authentication along with all the files you need.
The database you need for this project can be found in the databases folder, and is called
login.sql. Load up phphMyAdmin and import this SQL file, just like you did for the membertest
database in the previous section. When you import the file, the left side of phpMyAdmin should
look like this:
When you click on the login table in the login database, the right side of phpMyAdmin should
like like this (except for the first unencrypted row):
Those really are encrypted values in column L2, and not just somebody typing in really long and
complicated passwords. Let's see how to do encryption.
Click on the Structure tab at the top of phpMyAdmin to see how we've set up the various fields
in the table:
Set the ID field to be the primary key. (You did this in an earlier lesson, as well as setting an
Auto Increment.)
This lesson is part of an ongoing User Authentication tutorial. The first part is here: User
Authentication along with all the files you need.
The first script to take a look at in your login folder is signup.php. You can fire up your server
and try it out. What you'll see is a simple login page with textboxes for username and password,
as well as a Register button. It will look like this:
Type a username and password, and make a note of the them, as you'll be needing these details
for the login page.
Open up the signup.php script and take a look at the code. (It's one of the files you downloaded
from here: scripts.) The HTML for this form can be seen at the bottom of the page. There's
nothing special about it. But notice that there's a PHP print statement in the HTML Body section:
The first few line of the script, though, just set up some variables:
$uname = "";
$pword = "";
$errorMessage = "";
The next part of the code is where we check to see if the form has been POSTED or not (was the
Register button clicked):
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
}
$uname = $_POST['username'];
$pword = $_POST['password'];
require '../../configure.php';
$database = "login";
$db_found = new mysqli(DB_SERVER, DB_USER, DB_PASS, $database );
We then create a new mysqli object passing in all those constants we set up in the configure file.
(SEE HERE, if you skipped this lesson.)
If the database was found, then the variable called $db_found will be true. We check for this in
the next lines:
if ($db_found) {
}
else {
If the database isn't found, then some text is added to the error message variable. If the database
is found, then we set up a prepared statement:
$SQL->bind_param('s', $uname);
$SQL->execute();
We only want to select the L1 column, which is the username. We're going to make sure that this
column is a unique value, meaning you can't have two people with the same username. To do
that, we need to get the results from the SQL query:
$result = $SQL->get_result();
If any results are returned, then we know that the username is taken. So we can display a
message:
if ($result->num_rows > 0) {
If no results are returned, then we can go ahead and add the chosen username to the database.
else {
The first line of this new code is where we set up the encryption:
The PHP function password_hash is an inbuilt one. In between the round brackets of
password_hash you need some text you want to encrypt. After a comma, you specify the
encryption algorithm that you want to use. You can either use PASSWORD_DEFAULT or
PASSWORD_BCRYPT here. These two are inbuilt constants. PASSWORD_DEFAULT gets
you the bcrypt algorithm. It's recommended that you created a field in your database 255
characters long. Rather confusingly, PASSWORD_BCRYPT use the crypt_blowfish algorithm.
Once password_hash has done its work, it will either return you a hashed (and salted) password,
or it will return false, if something went wrong. (You could set up an if statement to test for this,
if you wanted.)
So we're INSERT INTO with our two database table fields L1 and L2. The VALUES are
question mark placeholders. The next line binds these parameters:
$SQL->execute();
header ("Location: login.php");
The last line redirects the new user to the login page. If you took the user's email address you
could also send them something to let them know they have been successful. But please don't
email them their new password in plain text!
This lesson is part of an ongoing User Authentication tutorial. The first part is here: User
Authentication along with all the files you need.
For the login page, what we'll do is to get the username and password from textboxes on a form.
We'll first see if the username exists in the database. If it does, then we can go ahead and check
the password using an inbuilt PHP function called password_verify. If the login is successful,
we can do two things: one, set up a session variable that can be used on all pages on your site.
This sessions variable is used so that users who aren't logged in won't be able to see any pages,
but are redirected to the login page. The other thing we'll do is to redirect a successfully logged
in user to the correct page. After all, you don't want users hanging about on the login page.
So open up the script called login.php and take a look at the code. (It's one of the files you
downloaded from here: scripts.)
The bottom of the page is the HTML for the user form. It's just two textboxes and a Submit
button. The PHP code starts by setting up some variables:
$uname = "";
$pword = "";
$errorMessage = "";
The connection to the server and database is the same as before (use require to get the configure
file you set up, and get those constants.)
require '../../configure.php';
$database = "login";
$db_found = new mysqli(DB_SERVER, DB_USER, DB_PASS, $database );
The SQL selects all the records where the username matches the one provided:
$SQL->bind_param('s', $uname);
$SQL->execute();
$result = $SQL->get_result();
We only need to check if there is one result, as our signup page ensured that all usernames were
unique.
if ($result->num_rows == 1) {
(Although we've said "username FAILED", you probably don't want to be this explicit. The idea
is to not give any clues to an attacker. So you could just say something like "Login failed". For
testing purposes, though, we'd like to know why something went wrong.)
$db_field = $result->fetch_assoc();
The fetch_assoc function, remember, brings you back an array, with all positions in the array
filled with a field in the database row that was returned. The $db_field variable would then look
like this:
The one we want to check is the L2 field, which contains the password:
if (password_verify($pword, $db_field['L2'])) {
}
else {
}
password_verify($pword, $db_field['L2'])
To check a password in a database table, you can use the inbuilt PHP function password_verify.
The password_verify function needs two things: the password you want to check, and the
password hash you want to check it against. For us, the password hash is in the $db_field['L2']
variable. The password inside of the $pword variable came from the textbox on the form. When
you compare the two, you'll either have TRUE, the password is correct, or FALSE, the password
is wrong.
If the password and username are OK, we have these three lines of code for the IF Statement:
session_start();
$_SESSION['login'] = "1";
header ("Location: page1.php");
So that a user can be remembered across different web pages, you can use something called a
Session. A session is simply the time spent at a particular site or sites. You can store values with
sessions, and these values will be available to all pages on the site. When you close your
browser, the sessions will end. There are quite a lot of ways to use sessions, but we're only
interested in saving a value so that it can be referred to across different pages.
To set up a session variable, you need to issue the session start command:
session_start( );
This starts a PHP session. To set up a session variable that you can use to store values, you use
this:
$_SESSION[ ]
$_SESSION['login'] = "1";
After the script runs, you'll have a session variable called 'login' that is set to a value of 1, if the
user is OK. You can then use the "header" function to redirect the user to the page on your site
for members, page1.php in the code above:
else {
First, we're placing a something in the errorMessage variable: Invalid Login. This will be
displayed at the bottom of the HTML form. Next, we start a session and then place a blank value
in the login sessions:
session_start();
$_SESSION['login'] = '';
We're using the same session name (login), but this time we set it to a blank string. If the user
tries to gain access to a restricted part of the site, we'll check for a blank string. A blank string
means that the user hasn't logged on successfully, so we'll redirect them to the login page.
A note of caution here. If you switch cookies off in your browser, the script above may refuse to
work! This is because when you use session_start, PHP sends the browser something called a
session ID. This is a long string of letters and numbers. PHP attempts to save the session ID as a
cookie. But it only does this if a line in php.ini from your Apache server is set. This line:
session.use_cookies = 1
If you set this value to 0, then you should be able to log on whether cookies are set or not. The
problem is, there's a good chance that you can't set this to zero. Especially if you have web
hosting with someone else. The solution, in that case, is to check whether cookies are enabled or
not.
You should then find plenty of ideas for scripts to check if cookies are enabled in the browser.
In the next part, we'll check if the user is logged in, and offer the option to logout.
This lesson is part of an ongoing User Authentication tutorial. The first part is here: User
Authentication along with all the files you need.
If you open up the file called page1.php (It's one of the files you downloaded from here:
scripts.), you'll see some PHP code at the top:
<?PHP
session_start();
?>
Again, we first start a PHP session. The IF Statement that comes next is quite complex. But
we're testing for two things: has a user session called login been set? And is this session a blank
string?
To check if a session is set you can use the inbuilt function isset. We're using the NOT operator
before it. (The NOT operator is an exclamation mark.) So we're saying, "IF the session is NOT
set". The session might be set, but may have a "1" in it. We also need to check if the session
called login is a NOT blank string. If both of these things fail then we can redirect to the
login.php page, as it means that the user is not logged in.
For every page in your site, if you have the above script at the top of your page, it will redirect a
user if they are not logged in. That way, you can protect your pages from non-members. If they
are logged in, they will be able to view the page.
Logging out
If you have a look at the code for logout.php you'll see the following:
<?PHP
session_start();
session_destroy();
?>
This is all you need to log a user out: you start a session, and then issue the session_destroy
command. All you need is a link to this page from anywhere on your site. The link would be
something like this as your HTML:
When the user clicks this link, they will be taken to the page with the code that destroys the
session.
Conclusion
Although our login/signup scripts are by no means complete, we hope that they've given you
something to think about. In particular, that these types of scripts are not as simple as you first
thought. There are quite a few ready-made login scripts that will do the job for you, but we hope
that you will develop your own!
In this set of tutorials, you will learn how to write a survey app in PHP. To get started, you need
the survey folder, which is in the scripts folder that you downloaded. Copy the survey folder over
to the www directory on your PHP server. (Wampserver users can click on the green icon in the
bottom right of Windows. From the menu that appears, click www directory to open the folder.)
You'll also need the database, which can be found in the databases folder, and is called
survey.sql. Load up phphMyAdmin and import this SQL file, just like you did for the
membertest and login databases in previous sections. When you import the survey file, the left
side of phpMyAdmin should look like this:
So the database is called survey and the table in the database is called tblsurvey.
Click on tblsurvey. This will take you to the browse tab in phpMyAdmin, where you can see
three rows already set up:
Click on the Structure tab at the top. You'll see this (we've chopped a few columns off from the
right-hand side):
In the Name column on the left, we have our table fields. There are eight in all: ID, Question,
OptionA, OptionB, OptionC, VotedA, VotedB, VotedC. OptionA, OptionB and OptionC are
where the three choices go when you set a new question. These three all have the Type varchar,
and can be 255 characters in length. VotedA, VotedB and VotedC are all integer types. These
You can, if you want, edit the values in the table. For example, the choice for OptionA in the
"Do you like Facebook?" question says "yes, it's brilliant!". We'd like the "yes" to have a capital
letter Y at the start. To edit just this row, put a check in the box to the left of Edit:
Now click on Edit. You will be taken to the Insert page. Amend the OptionA text area. Change
the lowercase y to and uppercase letter:
The next thing we'll do is to take a look at how the app works.
This lesson is part of an ongoing Survey/Poll tutorial. The first part is here: Build your own
Survey/Poll, along with all the files you need.
In the previous lesson, you set up the database for the PHP survey app. In this lesson, you'll see
how it all works.
Have a look at the files for the survey. The files in the scripts/survey folder that you downloaded
are these:
survey.php
setSurvey.php
setQuestion.php
process.php
viewResults.php
red.jpg
Start your server and take a look at how everything works. The first page to examine is the
survey.php file. Once you've copied over all the files correctly, the address on your localhost for
the survey.php file should be this:
http://localhost/survey/survey.php
Click the View Results button and you'll see this page (viewResults.php):
The question is repeated at the top, and the choices are there on the left. There also values for the
percentages of votes, as well as the actual number who voted. (You could put all this in a HTML
table, so that everything is neatly aligned.)
Go back to the survey page and you'll notice that same question appears. This is the default
question. How, then, do you change the question?
Load up the page called setSurvey.php and you'll see this page:
These questions are being pulled from the survey database. They are then added to a HTML
dropdown list. Select a question from the list and then click the button to set that question as
your survey. You will then be taken back to the survey page, where you will see the question
displayed:
The first thing you'll want to do when testing this page is to open up the code for the
process.php page. Locate the following line:
Comment this line out, otherwise you'll get the message "You've already voted" whenever you
try to add a new vote to your database. (Don't forget to uncomment the line, if it's going onto
your website.) You'll see how the process page works a little later.
To set new questions in the survey database, load up setQuestion.php. You'll see this:
Type in a new question in the textbox at the top, and the three options in the textboxes below
that. To add the question to the database, click the Set this Question button.
The other two files in the scripts folder are process.php and red.jpg. The process page is called
from the survey.php file and is used to add a vote to the database. It also detects if the user has
already voted, and displays a suitable message. You'll see how all this works during these
tutorials.
The red.jpg file is used on the viewResults page. It's the horizontal bar that tells the user what
percentage of voters selected a particular option. You can replace this red bar with anything you
like.
In the next lesson, you'll take a look at the PHP code to set a question for the survey.
This lesson is part of an ongoing Survey/Poll tutorial. The first part is here: Build your own
Survey/Poll, along with all the files you need.
In the previous part of this lesson, you had a look at the structure for the Survey database.The
first PHP page we'll take a look at is the setSurvey.php file, which is in the scripts/survey folder
that you downloaded. The is where we set a question for the survey. As a reminder, the page
looks like this in a browser:
Using your favourite text editor, open up the file called setQuestion.php again, and take a look
at the code:
PHP code for setQuestion (opens in a new browser tab as a text file)
At the very top of the page, we have our require line, which gets the constants for the database
and server connection. Notice that the file location reference has two sets of dot/dot/slash at the
start. This is because we have placed our configure file outside of the web root folder. You
should change the file reference to match where you have saved your own configure file.
After getting a reference to the configure file, we set up some variables. Most of the variables are
set to blank strings. Except these two:
We have to construct our own HTML dropdown box with PHP. If you were doing it purely in
HTML then a dropdown box looks like this:
<SELECT>
The above HTML code would give you a dropdown list with two items in it. So we need to add
the two SELECT parts, the beginning and the end ones, using PHP code. We'll be filling in the
OPTION parts later.
When the page first loads, we'll fill it with options from the database table. However, we need to
detect if the button on the form was clicked. The next part of our PHP code detects that:
if (isset($_GET['Submit1'])) {
$getDropdownID = $_GET['drop1'];
header ("Location: survey.php?h1=" . $getDropdownID);
We'll come back to this code later. But it checks if a HTML Form object called Submit1 has
been set. This form object is the button. We want to redirect to the survey page, where the survey
the user selected will be loaded.
The first thing the rest of the code does is to connect to the server and database. We then have
this line:
if ($stmt) {
The first line is a prepared statement. In between round brackets, we have this:
In previous tutorials, we selected all the records from a database table. We used the asterisk
symbol (*):
However, you don't need to select every field from your table. You can select only the fields
(table columns) that you need. We only need the ID number and the question, so we're just
selecting these two fields. The question will be added to the dropdown box. The ID number is
placed in a hidden HTML tag. When we redirect to the survey page, survey.php will grab this ID
and use it to pull the correct records from the table.
if ($stmt) {
}
else {
If the SQL is successful then we execute it, and get the results:
$stmt->execute();
$res = $stmt->get_result();
Next, we test if the number of rows is greater than zero. If it's not we print a message:
if ($res->num_rows > 0) {
else {
If rows were found, we can loop round and construct our dropdown HTML code:
$qID = $row['ID'];
$question = $row['Question'];
$dropdown = $dropdown . "<OPTION VALUE='" . $qID . "'>" . $question . "</OPTION>" .
"<BR>";
$qID = $row['ID'];
$question = $row['Question'];
The row ID goes into the $qID variable we set up at the top of the code; the question from the
row goes into a variable of its own, $question. Once we have these values, we can use them to
construct the HTML:
We only need the OPTION part of the SELECT tag, here. We're adding the $qID as the VALUE
parameter. The question itself goes into between pointy brackets.
Once the loop has done its work, when can piece together the whole of the HTML for a
dropdown list:
We can use the $wholeHTML variable in the FORM part of the HTML. Here's the HTML for
the FORM:
</FORM>
The ACTION for this form is to send it to itself for processing. It does this when the button with
the TYPE called "Submit" is clicked. The NAME of this Submit button is "Submit1".
We detect if the button on the form was clicked with this PHP code, which is at the top:
if (isset($_GET['Submit1'])) {
$getDropdownID = $_GET['drop1'];
This detects if the button with the NAME Submit1 was clicked. If it was, we have this as the first
line:
$getDropdownID = $_GET['drop1'];
We're trying to get the NAME of the HTML SELECT dropdown box. If you remember, we had
this for the SELECT:
This is where the name "drop1" comes from. Once we have the NAME of the SELECT
dropdown list, we can grab whatever VALUE was selected from the list and store it in the
variable called $getDropdownID. The VALUES are coming from this part of the code:
Each OPTION VALUE will be different, and comes from the ID field in the database table.
We want to redirect to the survey.PHP page. But we need this page to have an ID. That way, the
code for the survey page can grab the ID value and use it to look up the correct survey. Because
we're using GET as our FORMs METHOD, we can do this with the web address:
survey.php?h1="
The question mark means a value follows. The name of the value is something that we have
called h1. But you can call it almost anything you want. After an equal sign, you type the value
that you want to send to the page. In our case, this value is contained in the variable
$getDropdownID.
This lesson is part of an ongoing Survey/Poll tutorial. The first part is here: Build your own
Survey/Poll, along with all the files you need.
In the previous part lesson, you had a look at the PHP code to set a question for your survey.
We'll now look at the code for the actual survey.In a web browser, it looks like this:
The HTML form for this consists of three RADIO tags and two SUBMIT tags. (The SUBMIT
tag gets you a button.) Here's the HTML for the form:
</FORM>
</FORM>
The thing to note here is that there are two forms between the BODY tags. The first, with the
NAME form1, is for the "Click here to Vote" button. The ACTION for this form is process.php.
This is a separate file that we'll look at soon. The second form, with the NAME form2, is for the
There are one or two things to note about form1. First, there's a print statement at the top:
This will print out the question. The second thing to note is the HTML RADIO buttons:
<INPUT TYPE = 'Radio' Name ='q' value= 'A' <?PHP print $answerA; ?>><?PHP print $A; ?>
<INPUT TYPE = 'Radio' Name ='q' value= 'B' <?PHP print $answerB; ?>><?PHP print $B; ?>
<INPUT TYPE = 'Radio' Name ='q' value= 'C' <?PHP print $answerC; ?>><?PHP print $C; ?>
All three RADIO buttons have the same NAME: 'q'. This is so that they are treated as one group.
The VALUE is either A, B, or C. We'll get the value with PHP code. The first print statements
($answerA, $answer and $answerC) are for the CHECKED property of RADIO buttons. We
need to know which button the user selected (checked). The second print statements ($A, $B,
$C) are for the three choices that we'll pull from the database table.
The HTML for form2 is just a HIDDEN tag. It has the NAME h1 and prints an ID. We'll grab
these when the form is sent to the viewResults.php page.
Let's have a look at the PHP code for survey.php. It's this:
PHP code for survey (opens in a new browser tab as a text file)
The first part of the code is for getting a value from the setSurvey page. If you remember, this
page has a dropdown list where you can set a question for your survey. It passes over the ID
number from the database table. This is what we're getting:
if (isset($_GET['h1'])) {
$qID = $_GET['h1'];
} else {
$qID = 1;
The isset part will only activate if it can GET a value with called h1. This h1 value is passed over
from setSurvey.php. If all is OK, then we place the ID from setSurvey into a variable called
$qID. This will contain an ID from the database table. If it can't get a value for h1 then we're
setting a default value for $qID - 1. This means row 1 from the table. There would be a problem
here, if you didn't have a row with an ID of 1. So you could query the database and grab any
$answerA = 'unchecked';
$answerB = 'unchecked';
$answerC = 'unchecked';
$A = "";
$B = "";
$C = "";
If a question can't be set, we're storing some defaults for the question, and the three choices, A, B
and C. We're also leaving the RADIO buttons unchecked.
After attempting to contact the server and database, we have our prepared statement:
The only columns we need are ID, Question, OptionA, OptionB and OptionC. But we need to
match an ID, which is why we have the question mark after the WHERE clause.
$stmt->bind_param('i', $qID);
The letter 'I' means Integer, because that's what we set up our ID field as. The ID itself will be
held in the variable called $qID.
Next, we execute the statement and try to get some rows back:
$stmt->execute();
$res = $stmt->get_result();
if ($res->num_rows > 0) {
$question = $row['Question'];
$A = $row['OptionA'];
$B = $row['OptionB'];
$C = $row['OptionC'];
So we access the Question, OptionA, OptionB and OptionC fields from the database and place
the values into the variables called $question, $A, $B, $C.
And that's all we need to do. The rest of the PHP code is just some error checking, with lots of
else parts to the if statements.
When the user selects an option, and activates the "Click here to vote" button, then they will be
sent to the process.php page. That $qID variable above will be sent to the process page. Also
sent to the process page is the choice the user made (A, B or C).
The process page is used for processing the choice that a user made in the survey. That choice is
added to the survey database table, and a suitable message is displayed once the vote has been
added. To do all that, it needs two things from the survey.php page: the choice that the user
made (A, B or C), and a question row ID from the table.
The row ID is contained in the $qID variable from the survey page. We placed this in a HIDDEN
HTML tag:
<INPUT TYPE = "Hidden" Name = "h1" VALUE = <?PHP print $qID; ?>>
On the process page, we can use GET to grab that ID, simply by using the NAME value, which
was h1. When a RADIO button is clicked, you can also just GET the NAME value. Each
RADIO button was given the NAME 'q':
<INPUT TYPE = 'Radio' Name ='q' value= 'A' <?PHP print $answerA; ?>><?PHP print $A; ?>
<INPUT TYPE = 'Radio' Name ='q' value= 'B' <?PHP print $answerB; ?>><?PHP print $B; ?>
<INPUT TYPE = 'Radio' Name ='q' value= 'C' <?PHP print $answerC; ?>><?PHP print $C; ?>
If you use $_GET['q'] then you can grab the VALUE, which we have as A, B or C, in the code
above. Here's the entire code for the process.php page:
$_SESSION['hasVoted'] = '1';
Comment this line out, otherwise you'll get the message "You've already voted" whenever you
try to add a new vote to your database. You may even need to close your browser down and open
it up again, depending how you've got your cookies set up. Don't forget to uncomment the line, if
it's going onto your website. But it's there to set a session variable called hasVoted. We can
check for this at the top of the code:
session_start();
if ((isset($_SESSION['hasVoted']))) {
if ($_SESSION['hasVoted'] = '1') {
This checks if a session called hasVoted has been set. We next check if the hasVoted session is
set to a value of 1. If both of these things are true then it means that the user has already voted.
(Of course, you could just clear out your cookies and vote again. But this is not exactly an app
that guards the Crown Jewels! A more robust app might create a temporary database table and
record that the user has voted there.)
If the user hasn't voted, the else part of the if statement is executed. First up is this piece of code:
$selected_radio = $_GET['q'];
$idNumber = $_GET['h1'];
This checks if the Submit button on the previous page was clicked. It also checks if the q
variable is set. This q variable, remember, is holding a value from our RADIO buttons. It will be
A, B, or C, depending on which option was selected.
If both of these things are true, we can go ahead and store the values into variables:
$selected_radio = $_GET['q'];
$idNumber = $_GET['h1'];
The next part of the code connects to the server and database, where we create a new mysqli
object (you've met this code before):
if ($db_found) {
If the database and server are found, we need to check of the selected RADIO button hold a
value of A, B or C:
if($selected_radio == "A") {
}
else if($selected_radio == "B") {
}
else if($selected_radio == "C") {
}
else {
If $selected_radio is not A, B or C then we print a message: Error - could not record vote.
The code for these if … elseif … statements, first builds a prepared statement:
We want to UPDATE the table and SET a new value. Notice this part:
VotedA = VotedA + 1
The field in the table called votedA will be incremented by 1, with this code. The WHERE part
at the end is for matching the correct row in the table with the ID value we're going to be passing
it.
$stmt = $db->prepare($sql);
$stmt->bind_param('i', $id);
$stmt->execute();
//$_SESSION['hasVoted'] = '1';
We're passing the function three things: the database object ($db) the SQL we want to use for
prepare, and that ID number. These are used on the first two lines:
$stmt = $db->prepare($sql);
$stmt->bind_param('i', $id);
The parameters for bind are i and $id. The i stands for integer, and the $id variable holds the row
ID for the surveytable.
$_SESSION['hasVoted'] = '1';
This places a value of 1 in the session called hasVoted. Once we set something in the session
variable, it means the user can't vote over and over again, because they'll get that message,
"Already voted".
And that's about it for the process.php page. The whole point of the code is to record a vote in
the database, and prevent users from voting repeatedly.
This lesson is part of an ongoing Survey/Poll tutorial. The first part is here: Build your own
Survey/Poll, along with all the files you need.
If you remember from the survey page, we had button that said "View Results". This button was
part of a form. The form had a HTML hidden tag. This hidden tag had the ID number for a row
in our database table. When the button is clicked, the form passes this hidden ID number of to
the viewResults.php page. The viewResults page uses this row ID to pull records from the table.
Here's all the PHP code for viewResults:
PHP code for survey results (opens in a new browser tab as a text file)
At the very top of the code, we've set up quite a lot of variables. Ten of those variables are for
the red horizontal bars you see in the image above. The other variables will hold information
from the database table. The first real bit of code is the if statement:
This checks if two things are set: the Submit button from the survey form, and the hidden
variable, which we've called h1. If they are, we can GET the value of h1:
$qNum = $_GET['h1'];
After connecting to the server and database, we have this for our SQL:
This time, we do want all the records from the table. But only WHERE we've found a matching
ID field.
if ($SQL) {
}
This will return true if the SQL is OK, and false if it's not.
Inside the SQL test, we have bind the parameters and execute:
$SQL->bind_param('i', $qNum);
$SQL->execute();
Because the ID field is an integer in our table, we need the letter i as the first parameter between
the round brackets of bind_param. The $qNum variable hold the actual ID.
$result = $SQL->get_result();
if ($result->num_rows > 0) {
}
If we successfully return some rows, we can get an array of values from the database table:
$db_field = $result->fetch_assoc();
Now we can go ahead and fill our variables that we set up at the top of the code:
$question = $db_field['Question'];
$answerA = $db_field['OptionA'];
$answerB = $db_field['OptionB'];
$answerC = $db_field['OptionC'];
$qA = $db_field['VotedA'];
$qB = $db_field['VotedB'];
$qC = $db_field['VotedC'];
Every field from our table is accessed and placed into variables. We need all of these values
back, as we're going to be displaying them on the web page. So we get what the question was,
and the three choices that the user had. We also get whether they voted A, B or C.
We want to say what percentage of the vote a particular choice received. So option A might have
received 50 percent of the vote, option B 25 percent, and option C 25 percent. The next few lines
of code do just that. Here's the PHP code we have for option A:
The first line gets the total number of votes. We then turn this into a percentage by multiplying
the votes cast for A by 100 and then dividing by the grand total of votes. The third line above
just uses the inbuilt PHP function floor to round the answer down.
The next few lines get the percentage values for options B and C.
Most of the rest of the code is taken up with building a HTML tag for an image. We want the red
bar image to stretch or shrink, depending on what percentage of the vote a choice received. As a
reminder, here's what an HTML image tag looks like:
If we hard-coded that, we'd get a red image that was 10 pixels high and 100 pixels wide.
But we want to build the HTML image tag with PHP. Here's the first three lines to do that:
$imgWidthA = $percentA * 2;
$imgWidthB = $percentB * 2;
$imgWidthC = $percentC * 2;
What we're doing here is multiplying the individual percentages by 2. If we didn't multiply the
image by 2, it would be really small and difficult to see. (You can multiply by a different
number, if you want a wider image.) We now have values for the WIDTH part of the HTML tag.
The HEIGHT value was something we hard-coded at the top of the page:
$imgHeight = 10;
If you want a taller red line then you can adjust this value.
$imgTagA = "<IMG SRC = 'red.jpg' Height = " . $imgHeight . " WIDTH = " . $imgWidthA.
">";
Here, we're using the concatenate operator (.) to join together the various parts of the IMG tag,
and placing it into a variable of its own ($imgTagA).
<body>
<?PHP
?>
</body>
First, we print the question out. Then we join together the various parts for each answer:
print $answerA . " " . $imgTagA . " " . $percentA . "% " . $qA . "<BR>";
We're printing the answer first (one of the three choices the user had). Then we have the IMG tag
which we built up earlier. Next comes the actual percentage, and finally the actual number of
votes cast for that choice. Here is a visual representation of where the various variables are
ending up:
Not much to do now, for the survey. The final part is adding new questions to the database.
This is fairly straightforward. You type your question into the textbox at the top, and type your
three options into the textboxes below that. Click the Set this Question button and it will add it to
the database.
PHP code - adding a new question (opens in a new browser tab as a text file)
<?PHP
require '../../configure.php';
if (isset($_GET['Sub1'])) {
$question = $_GET['question'];
$answerA = $_GET['AnswerA'];
$answerB = $_GET['AnswerB'];
$answerC = $_GET['AnswerC'];
$database = "survey";
if ($db_found) {
$SQL = "INSERT INTO tblsurvey (Question, OptionA, OptionB,
OptionC) VALUES (?,?,?,?)";
$stmt = $db_found->prepare($SQL);
if ($stmt) {
$stmt->bind_param('ssss', $question, $answerA,
$answerB, $answerC);
$stmt->execute();
The HTML uses four INPUT TYPES (Text) and a SUBMIT button. The FORM itself is has the
METHOD as GET, and the ACTION is to send it back to setQuestion.php for processing.
The first textbox has a MAXLENGTH attribute set. We have this as a value of 40, but you can
change this, if you want. The NAME properties for the textboxes are question, AnswerA,
AnswerB, and AnswerC. We'll need these names to grab the values entered into the textboxes.
n the PHP code, we first check that the Sub1 button is set. We then place the values from the
HTML form into variables:
$question = $_GET['question'];
$answerA = $_GET['AnswerA'];
$SQL = "INSERT INTO tblsurvey (Question, OptionA, OptionB, OptionC) VALUES (?,?,?,?)";
We're trying to access four fields in our database table Question, OptionA, OptionB, and
OptionC. We want to INSERT VALUES. There are four question marks between the round
brackets of VALUES, one for each of the four fields.
The first parameter uses four letter S's, one for each of the string values going into the table.
Once we execute this statement, we print out a friendly message, to tell the user that the question
has been added to the database.
And that's it for the survey walkthrough. Some of it, like adding a new question, is fairly
straightforward, while some of it is quite complex, if you're a beginner. But study the code, and
hopefully you'll gain a greater insight into how it all works. Try modifying it for your own needs,
and see how you get on. Good luck!