You are on page 1of 280

Beginners PHP

Copyright: Home and Learn/Ken Carney 2002
This Edition: Revised and Updated - 2008
Author: Ken Carney for Home and Learn
All rights reserved
PHP Contents
WHAT IS PHP, AND WHY DO I NEED IT? ----------------------------------------------------------- 7
WHAT YOU NEED TO GET STARTED---------------------------------------------------------------- 7
INSTALLING AND TESTING EASY PHP------------------------------------------------------------- 8
Troubleshooting------------------------------------------------------------------------------------------------------------------------15
Course Files -----------------------------------------------------------------------------------------------------------------------------15
WHAT IS A VARIABLE?--------------------------------------------------------------------------------- 17
PUTTING TEXT INTO VARIABLES ----------------------------------------------------------------- 19
VARIABLES - SOME PRACTICE --------------------------------------------------------------------- 20
MORE VARIABLE PRACTICE ------------------------------------------------------------------------ 24
Joining direct text and variable data----------------------------------------------------------------------------------------------25
Adding up in PHP---------------------------------------------------------------------------------------------------------------------25
SUBTRACT, DIVIDE ANDMULTIPLY-------------------------------------------------------------- 27
CONDITIONAL LOGIC---------------------------------------------------------------------------------- 33
If Statements ----------------------------------------------------------------------------------------------------------------------------34
Using If Statements -------------------------------------------------------------------------------------------------------------------36
if … else Statements------------------------------------------------------------------------------------------------------------------38
if … else if Statements ---------------------------------------------------------------------------------------------------------------39
MORE CONDITIONAL LOGIC------------------------------------------------------------------------ 43
Comparison Operators ---------------------------------------------------------------------------------------------------------------43
NOT Equal To--------------------------------------------------------------------------------------------------------------------------44
Less Than and Greater Than -------------------------------------------------------------------------------------------------------45
Less Than or Equal To and Greater Than or Equal To ---------------------------------------------------------------------46
The Switch Statement ----------------------------------------------------------------------------------------------------------------47
Logical Operators----------------------------------------------------------------------------------------------------------------------49
Boolean Values-------------------------------------------------------------------------------------------------------------------------51
Operator Precedence – a List-------------------------------------------------------------------------------------------------------53
HTML FORMS---------------------------------------------------------------------------------------------- 54
The HTML Form----------------------------------------------------------------------------------------------------------------------54
FORM Attributes ----------------------------------------------------------------------------------------------------------------------55
Method------------------------------------------------------------------------------------------------------------------------------------55
Post ----------------------------------------------------------------------------------------------------------------------------------------56
Action-------------------------------------------------------------------------------------------------------------------------------------56
Submit ------------------------------------------------------------------------------------------------------------------------------------57
Using PHP to get values from a HTML form---------------------------------------------------------------------------------57
Getting values from a Text Box---------------------------------------------------------------------------------------------------57
Checking if the Submit was clicked----------------------------------------------------------------------------------------------59
Setting the ACTION attribute to a different PHP page---------------------------------------------------------------------60
Keeping the data the user entered-------------------------------------------------------------------------------------------------62
How to handle other Form Elements with PHP-------------------------------------------------------------------------------64
Radio Buttons---------------------------------------------------------------------------------------------------------------------------64
Checkboxes------------------------------------------------------------------------------------------------------------------------------68
LOOPS -------------------------------------------------------------------------------------------------------- 74
For Loops --------------------------------------------------------------------------------------------------------------------------------74
A Times Table Programme ---------------------------------------------------------------------------------------------------------76
Code for the PHP Times Table ----------------------------------------------------------------------------------------------------77
While Loops-----------------------------------------------------------------------------------------------------------------------------80
Do While loops-------------------------------------------------------------------------------------------------------------------------81
The break statement-------------------------------------------------------------------------------------------------------------------82
For Each----------------------------------------------------------------------------------------------------------------------------------82
ARRAYS------------------------------------------------------------------------------------------------------ 83
What is an Array? ---------------------------------------------------------------------------------------------------------------------83
Setting up an Array -------------------------------------------------------------------------------------------------------------------83
Getting at the values stored in your arrays -------------------------------------------------------------------------------------87
Array - Using Text as Keys---------------------------------------------------------------------------------------------------------88
Arrays and For Each------------------------------------------------------------------------------------------------------------------89
Sorting Array values------------------------------------------------------------------------------------------------------------------90
Random Keys from an Array-------------------------------------------------------------------------------------------------------91
The count function --------------------------------------------------------------------------------------------------------------------91
Script One - Set up an array and print out the values -----------------------------------------------------------------------92
Script Two - Set up an array with your own Keys ---------------------------------------------------------------------------92
Script Three - Set up an array with mixed values ----------------------------------------------------------------------------93
Script four - Assign values to an array: Method Two example ----------------------------------------------------------93
Script Five - Looping round values in an array-------------------------------------------------------------------------------93
Script Six - Looping round values in an array: example 2-----------------------------------------------------------------94
Script Seven - Using text as Keys ------------------------------------------------------------------------------------------------94
Script Eight - Looping round an Associative array using For Each-----------------------------------------------------94
Script Nine - Sorting Arrays (Associative)-------------------------------------------------------------------------------------95
Script Ten - Sorting Arrays (Scalar) ---------------------------------------------------------------------------------------------95
STRING MANIPULATION------------------------------------------------------------------------------ 97
Changing Case--------------------------------------------------------------------------------------------------------------------------97
Trimming White Space --------------------------------------------------------------------------------------------------------------98
Shuffle characters----------------------------------------------------------------------------------------------------------------------99
Finding one string inside of another-------------------------------------------------------------------------------------------- 100
Splitting a line of text--------------------------------------------------------------------------------------------------------------- 102
Joining text into a single line----------------------------------------------------------------------------------------------------- 104
PHP and Escaping------------------------------------------------------------------------------------------------------------------- 105
String function list------------------------------------------------------------------------------------------------------------------- 106
PHP FUNCTIONS----------------------------------------------------------------------------------------- 111
What is a function?------------------------------------------------------------------------------------------------------------------ 111
Variable scope and functions----------------------------------------------------------------------------------------------------- 113
Functions and arguments---------------------------------------------------------------------------------------------------------- 114
A Function to check for blank Textboxes ------------------------------------------------------------------------------------ 116
Getting values out of functions-------------------------------------------------------------------------------------------------- 118
By Ref, By Val ----------------------------------------------------------------------------------------------------------------------- 120
PHP Server Variables -------------------------------------------------------------------------------------------------------------- 122
HTTP Header() Function---------------------------------------------------------------------------------------------------------- 123
Including scripts --------------------------------------------------------------------------------------------------------------------- 126
SECURITY ISSUES AND FORM ELEMENTS----------------------------------------------------- 128
htmlspecialchars() ------------------------------------------------------------------------------------------------------------------- 130
htmlentities()-------------------------------------------------------------------------------------------------------------------------- 131
strip_tags( )---------------------------------------------------------------------------------------------------------------------------- 132
WORKING WITH FILES IN PHP--------------------------------------------------------------------- 135
Opening a file------------------------------------------------------------------------------------------------------------------------- 135
Checking if the file exists --------------------------------------------------------------------------------------------------------- 141
Writing to files ----------------------------------------------------------------------------------------------------------------------- 141
Working with Comma delimited files (CSV files)------------------------------------------------------------------------- 143
Reading a text file line by line into an array – other options------------------------------------------------------------ 145
File Locations------------------------------------------------------------------------------------------------------------------------- 147
WORKING WITH DATE AND TIME FUNCTIONS IN PHP----------------------------------- 149
The date( ) function ----------------------------------------------------------------------------------------------------------------- 149
Day of the week Characters ------------------------------------------------------------------------------------------------------ 150
Month Characters-------------------------------------------------------------------------------------------------------------------- 150
Year Characters ---------------------------------------------------------------------------------------------------------------------- 150
Time Characters---------------------------------------------------------------------------------------------------------------------- 150
Other Date and Time Characters ------------------------------------------------------------------------------------------------ 151
PHP AND MYSQL----------------------------------------------------------------------------------------- 154
Creating a database using phpMyAdmin ------------------------------------------------------------------------------------- 156
Setting up Fields in your database tables ------------------------------------------------------------------------------------- 159
Adding records to a MySQL Table--------------------------------------------------------------------------------------------- 164
MANIPULATING A MYSQL DATABASE WITH PHP------------------------------------------ 168
How to access a MySQL database with PHP code ------------------------------------------------------------------------ 168
Reading records from a database------------------------------------------------------------------------------------------------ 172
Structured Query Language ------------------------------------------------------------------------------------------------------ 174
Adding records to a database table --------------------------------------------------------------------------------------------- 177
Using HTML Forms with your Database------------------------------------------------------------------------------------- 180
Magic Quotes ------------------------------------------------------------------------------------------------------------------------- 181
SQL injection ------------------------------------------------------------------------------------------------------------------------- 182
Limit the charcters that a user can enter: ------------------------------------------------------------------------------------- 186
OTHER THINGS YOU CANDO WITH SQL------------------------------------------------------- 187
Create a Table using SQL--------------------------------------------------------------------------------------------------------- 187
Updating a record in a table ------------------------------------------------------------------------------------------------------ 188
Deleting a record in a table ------------------------------------------------------------------------------------------------------- 189
Using WHERE to limit the data returned------------------------------------------------------------------------------------- 189
USER AUTHENTICATION WALKTHROUGH--------------------------------------------------- 191
The login page------------------------------------------------------------------------------------------------------------------------ 191
Checking if the user is logged on or not -------------------------------------------------------------------------------------- 197
Log Out--------------------------------------------------------------------------------------------------------------------------------- 198
Register a new user ----------------------------------------------------------------------------------------------------------------- 199
Other considerations---------------------------------------------------------------------------------------------------------------- 202
BUILD YOUR OWN SURVEY APPLICATION---------------------------------------------------- 204
Set a Question for your Survey-------------------------------------------------------------------------------------------------- 204
The database -------------------------------------------------------------------------------------------------------------------------- 206
Setting a question – the code----------------------------------------------------------------------------------------------------- 210
Add the Vote to the database----------------------------------------------------------------------------------------------------- 216
Viewing the results of the survey ----------------------------------------------------------------------------------------------- 218
Display a graphic for the results------------------------------------------------------------------------------------------------- 221
HOW TO BUILD AN ONLINE FORUM------------------------------------------------------------- 224
Setting up a Database for a bigger project------------------------------------------------------------------------------------ 228
The Forum Sections Table-------------------------------------------------------------------------------------------------------- 230
The Members Table----------------------------------------------------------------------------------------------------------------- 232
The Post Tables ---------------------------------------------------------------------------------------------------------------------- 233
The Reply Tables -------------------------------------------------------------------------------------------------------------------- 234
THE PHP CODE FOR THE FORUM----------------------------------------------------------------- 237
The forumTest.php page----------------------------------------------------------------------------------------------------------- 237
The pageThread.php page--------------------------------------------------------------------------------------------------------- 246
2D Arrays ------------------------------------------------------------------------------------------------------------------------------ 251
The pageReply.php Code---------------------------------------------------------------------------------------------------------- 258
The Reply Form---------------------------------------------------------------------------------------------------------------------- 265
The results.php page ---------------------------------------------------------------------------------------------------------------- 267
Posting a Topic on the Forum---------------------------------------------------------------------------------------------------- 270
The resultsP.php page -------------------------------------------------------------------------------------------------------------- 272
Final Project--------------------------------------------------------------------------------------------------------------------------- 276
What is PHP, and why do I need it?
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 comes
from the emarketing network dictionary (http://www.marketing.org .nz/emarket_
dictionary.php), and we prefer this version! They say: "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.
What you need to get started
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 "EasyPHP".
This allows you to test your PHP scripts on your own computer. Over a million
people have downloaded this software. It installs everything you need, if you have
a Windows PC (Win9x/Me/NT/2000/XP). 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.
Home and Learn
–8–
Apple Users
If you have OS 10, then try this guy's site to get up and running with PHP. The
link to click on is "PHP Apache Module (NEW version 5)"
http://www.entropy.ch/software/macosx/
Another useful page is:
http://farm.tucows.com/blog/_archives/2004/7/20/108833.html
You can also have a look at this site:
http://www.phpmac.com/browse.php?type=tut&cat=2
Linux Users
There's quite a few sites out there to help Linux users get up and running with the
Apache server and PHP. Here's two sites that are worth checking out:
http://www.e-gineer.com/v1/instructions/install-php4x-for-apache1xx-on-
linux.htm
http://www.phpfreaks.com/tutorials/12/0.php
If you know any better ones, we'd be interested in hearing from you!
Installing and Testing EASY PHP
OK, back to easy PHP 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):
http://www.easyphp.org/
Be sure to click the link for Installation Guide, as well as the link for Downloads.
The file you need to download is EasyPHP. Once you have downloaded the file,
double click to install.
If the installation goes well, you'll have an new entry on your Start >
Programmes menu. It should look something like this:
Beginners PHP
–9–
The newer version looks like this:
Note that the older, more stable version is 1.8. The newer version is 2.0. Pay
attention to which version you have, because it matters, as you’ll see below.
But click Easy PHP from the menu and you'll get this popping up:
If you get a green light for the Apache traffic sign, then your server is up and
running! (MySql is a database. We'll be using this in later tutorials. Don't worry
about it for now.) When the Apache server is loaded up, you'll see a black letter
"e" in your system tray (in the bottom right of your screen, where the clock is).
When Apache is running, a red square will be flashing on and off on the letter "e".
Right click to the letter "e" to see the following menu:
From here, you can stop the server, exit it, view help files, and see the
configuration pages. The Apache option on the configuration menu is an
interesting one. From here, you can change where your PHP files are stored. When
your scripts are run, they will then come from your location, and not the default
one. Look for this line:
Home and Learn
–10–
DocumentRoot "${path}/www"
To change the location, type a path to a directory of your choosing:
#DocumentRoot "${path}/www"
DocumentRoot "F:\myphp"
In the example above, we've changed the location to a folder on our "F" drive. The
hash (#) symbol before the old location means the line will be ignored.
But if you're not that adventurous, then you don't need to change anything!
You do, however, need to test if your PHP pages are displaying OK. To test it out,
start up your browser (Internet Explorer, Firefox, Opera, etc). If you have version
1.8 of EasyPHP, type the following into the address bar:
http://127.0.0.1/index.php
If you have version 2.0, type this instead:
http://127.0.0.1/home/index.php
Hit the enter key, and you should see a default index page:
The address 127.0.0.1, by the way, is the address of your own PC. Whenever
you're testing your web pages, type these numbers first. Then type a forward slash,
followed by the name of the PHP script you want to run. We'll now create a new
folder in the root directory, and create a new PHP page. So, do the following:
Beginners PHP
–11–
ۥOn your desktop, double click the icon for "My Computer"
€‚When you see a list of all your drives, double click the one where you
installed EasyPHP to (The F Drive, in our case. Probably "C", for you)
If you have EasyPHP version 1.8, locate a folder called PHP, and double click it.
You should see the following:
If you have EasyPHP version 2.0, then you need to navigate to your Program Files
folder. This is usually at C:\Program Files in XP. You should then see an EasyPHP
folder.
Double click the folder called "EasyPHP1-8", or “EasyPHP 2.0b1”, to see what's
inside of it. You should see a list of files and folders. Here’s the files and folders
for version 2.0:
Home and Learn
–12–
And here’s the folder view from version 1.8:
The folder we're looking for is called "www", which is in both versions. This is the
root folder mentioned on the index page above. Double click this folder to see the
following:
Beginners PHP
–13–
For version 1.8, the index.php file that you ran in your browser should appear.
This index file has now been moved to the home folder, for version 2.0. So you’ll
just have a blank folder. But for both versions, you'll be saving all of your scripts
to this directory, or folders in this directory, so it's a good idea to make a note of it.
Better yet, click Favorites > Add to favorites. You'll then have a shortcut to this
folder on your menu bar.
To create a new folder in your www folder, do the following (in windows):
€ƒClick File from then menu bar
€„From the File menu, click New > Folder
€…Rename the folder to "test" (without the quotation marks)
You now have a new directory (folder) in your root directory (the www one).
Copy and paste the following script into a text editor. (Something like Notepad
will do, if you're a Windows user. If you've never used Notepad, click Start > All
programmes > Accessories, then click Notepad.)
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php phpinfo(); ?>
</body>
</html>
Most of the script, except one line, is just plain HTML. The PHP code just
displays some information about PHP. You don't have to puzzle out what it all
means. The important part is, Does it work? Save your new script to the "test"
Home and Learn
–14–
folder you created. Call the file info.php. You should now have something like
this in your folder view:
If you can't see your new script in the test folder, then try again: it means you
didn't save it to the correct location. The image above is for EasyPHP version 1.8.
For version 2.0, only the address in the address bar will be different.
To test to see if it works, type the following address into your browser, and hit the
enter key:
http://127.0.0.1/test/info.php
The /test means "look in a folder called test". The /info.php part means "look for a
file called info.php. If all went well, you should be looking at the following page:
Beginners PHP
–15–
If you saw the above page, then congratulations! Your PHP server is up and
running, and you can make a start scripting PHP pages. Incidentally, another way
to refer to your own PC is with "localhost". Try replacing this address:
http://127.0.0.1/test/info.php
with this one:
http://localhost/test/info.php
You should still see the same page. You can use either 127.0.0.1 or localhost, from
now on - it's up to you.
We'll assume that everything is now up and running, though. So it's time to make a
start learning PHP. The first thing you'll be learning is all about variables. Good
luck!
Troubleshooting
If you don't see the info.php page, then make sure your Apache server is still
running (can you see the black "e" with the red flashing square?). If the Apache
server is not running, then you'll need to start it, like we did above. If it is running,
but you still can't see the PHP page above, try the following:
۠Make sure you have copied and pasted the script exactly as it is above
€‡If you can see the index.php ok, but not the info.php, then make sure you
have saved the script to the right folder, and with the file names exactly as
they are above
€ˆIf you can't see either page, and apache is running, try the help files at
http://www.easyphp.org/faq.php3
(Unfortunately, we can't answer questions about EasyPHP, as it's not our
software.)
Course Files
As well as getting your server up and running, you'll also need our Home and
Learn Course files. These can be downloaded from our website at the following
address:
Home and Learn
–16–
www.homeandlearn.co.uk/downloads/downloads.html
Once on the page, click the link for your course book, and save the Zip file to your
own hard drive. If you have any problems downloading the files, please contact us
at the following email address:
enquiry@homeandlearn.co.uk
You can now make a start. Up first – variables. Good luck with your
programming!
Beginners PHP
–17–
What is a Variable?
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
Home and Learn
–18–
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:
$total_clothes = $mr_coats + $mrs_shoes;
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;
Beginners PHP
–19–
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;
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.
Putting Text into variables
You can also put text into your variables. Suppose you want to know something
about the coats you own. Are they Winter coats? Jackets? Summer coats? You
decide to catalogue this, as well. You can put direct text into your variables. You
do it in a similar way to storing numbers:
$coats1 = "Winter Coats";
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:
$coats1 = 'Winter Coats';
But you can't do this:
$coats1 = 'Winter Coats";
In the above line, we've started with a single quote and ended with a double quote.
This will get you an error.
We can store other text in the same way:
$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.
Home and Learn
–20–
Variables - Some Practice
In the previous section, you saw what variables are: storage areas to hold things
like numbers and text. You tell PHP to remember these values because you want
to do something with them. In this section, you'll get some practice using
variables. Off we go.
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>Outputting text</title>
</head>
<body>
<?php print("It Worked!"); ?>
</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, as
explained at the start of the book. To run the page, start your browser up and type
this in the address bar:
http://127.0.0.1/variables.php
Or this:
http://localhost/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://127.0.0.1/FolderName/variables.php
Beginners PHP
–21–
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 weren't successful, make sure that your server is up and running. If you're
using easyPHP, you should see an icon in the bottom right of your screen. It will
be the letter "e". A red square will be flashing, if the server is running.)
The PHP script is only one line long:
<?php print("It Worked!"); ?>
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 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:
<?php print("It Worked!"); ?>
To this:
<?php
print("It Worked!");
?>
Home and Learn
–22–
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:
<?php
$test_String = "It Worked!";
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:
print($test_String);
Then add some comments ...
<?php
//--------------TESTING VARIABLES------------
$test_String = "It Worked!";
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:
<?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.
*/
$test_String = "It Worked!";
print($test_String);
?>
Beginners PHP
–23–
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.
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.
Now that you're up and running, we'll do some more variable work in the next
section.
Home and Learn
–24–
More Variable Practice
In the previous section, you started to work with variables. You outputted text to a
page. In this section, you'll do some more work with variables, and learn how to
do your sums with PHP.
Now that you can print text to a page, let's try some numbers. Start with the basic
PHP page again, and save your work as variables2.php:
<html>
<head>
<title>More on Variables</title>
</head>
<body>
<?php
print ("Basic Page");
?>
</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:
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!
TIP: We recommend you use single quotes for your direct text, and NOT double
quotes - there's fewer hassles if you do!
Beginners PHP
–25–
Joining direct text and variable data
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?
You can also do this sort of thing:
<?php
$first_number = 10;
print ('My variable contains the value of ' . $first_number);
?>
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.
Adding up 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 above open, 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:
Home and Learn
–26–
<?php
$first_number = 10;
$second_number = 20;
$sum_total = $first_number + $second_number;
$direct_text = 'The two variables added together = ';
print ($direct_text . $sum_total);
?>
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:
$sum_total = $first_number + $second_number;
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 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.
To print out the answer, we've used concatenation:
print ($direct_text . $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:
$sum_total = $first_number + $second_number;
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.
Beginners PHP
–27–
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:
print (10 + 20 + 30);
Or even this:
$number = 10;
print ($number + 30);
But the point is the same - use the plus symbol (+) to add up.
Subtract, Divide and Multiply
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.
Subtraction
To add up using PHP variables, you did this:
<?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:
$sum_total = $second_number - $first_number;
Home and Learn
–28–
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);
?>
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;
$sum_total = $third_number - $second_number + $first_number;
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:
Beginners PHP
–29–
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.
PHP and Multiplication
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:
<?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;
$sum_total = $third_number * $second_number * $first_number;
print ($sum_total);
?>
Home and Learn
–30–
And you can even do this:
$sum_total = $third_number * $second_number * 10;
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;
$sum_total = $third_number + $second_number * $first_number;
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;
Then it moves on to the addition. It doesn't do this first:
$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.
Beginners PHP
–31–
PHP and division
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
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.
Home and Learn
–32–
Floating point numbers
A floating point number is one that has a dot in it, like 0.5 and 10.8. You don't
need any special syntax to set these types of numbers up. Here's an example for
you to try:
<?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!
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):
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
Use a print statement to output your answer.
Beginners PHP
–33–
Conditional Logic
You saw in the last section that variables are storage areas for your text and
numbers. But 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.
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:
"If I turn the volume up on my stereo, will the neighbours be pleased?"
"If spend all my money on a new pair of shoes, will it make me happy?"
"If I study this course, will it improve my web site?"
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."
In PHP, you use the "IF" word like this:
if ($User_Name == "authentic") {
//Code to let user access the site here;
}
Without any checking, the if statement looks like this:
if ( ) {
}
Home and Learn
–34–
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") }
//Code to Let user access the site here;
{
And so will this:
if ($User_Name == "authentic") {
//Code to Let user access the site here;
{
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) {
//your code here;
}
To clarify things, let's have a more practical example.
If Statements
In this lesson, we'll use if statements to display an image on the page. (This lesson
continues on from our introduction to Conditional Logic---WEB SITE ONLY)
You can use the print statement to "print out" HTML code. As an example, take
the following HTML code to display an image:
<IMG SRC =church.jpg>
Beginners PHP
–35–
Just plain HTML. But you can put that code inside of the print statement:
print ("<IMG SRC =images/church.jpg>");
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 downloaded at the start of the book, in the folder called images.
Copy this images folder to your www (root) directory. Then try the following
script:
<?PHP
print ("<IMG SRC =images/church.jpg>");
?>
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:
Let's use that same line of code above to illustrate if statements.
Home and Learn
–36–
Using If Statements
We can use an if statement to display our image. If the user selected "church", then
display the church image. If the user selected "kitten", then display the kitten
image. Here's some code:
<?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.
The first two lines just set up some variables:
$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:
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”.
What we want to say is:
"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!
Beginners PHP
–37–
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) {
print ("<IMG SRC =images/kitten.jpg>");
}
You need the semi-colon at the end of the print statement.
But if your if statement only runs to one line, you can just do this:
if ($kitten_image == 1) { print ("<IMG SRC =images/kitten.jpg>"); }
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) {
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:
Home and Learn
–38–
print ("<IMG SRC =images/church.jpg>");
if … else Statements
Instead of using two if statements, however, 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>");
}
?>
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.
The syntax for the if else statement is this:
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;
Beginners PHP
–39–
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 {
print ("<IMG SRC =images/church.jpg>");
}
So the church image gets displayed. Change your two variables from this:
$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?
if … else if Statements
You can also add “else if” parts to your If Statements. The syntax is this:
else if (another_condition_to_test) {
}
Change your code to this, to see how else if works:
<?PHP
$kitten_image = 1;
$church_image = 0;
Home and Learn
–40–
if ($kitten_image == 1) {
print ("<IMG SRC =images/kitten.jpg>");
}
else if ($church_image == 1){
print ("<IMG SRC =images/church.jpg>");
}
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){
print ("<IMG SRC =images/church.jpg>");
}
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;
Beginners PHP
–41–
to this:
$kitten_image = 0;
$church_image = 0;
Then run your code again. What do you expect to happen?
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.
Here’s the entire script:
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<form Name = "f1" action="selectPicture.php" method="post">
<select name="picture">
<option value="none">Select a Picture</option>
<option value="church">Church</option>
<option value="kitten">Kitten</option>
<option value="planet">Planet</option>
<option value="cartoon">Cartoon</option>
<option value="space">Space Image</option>
<option value="abstract">Photoshop Abstract</option>
</select>
<input type="submit" name = "Submit" Value = "Choose an Image">
</form>
<?PHP
if (isset($_POST['Submit'])) {
$picture = $_POST['picture'];
Home and Learn
–42–
if ($picture = = "church") {
print ("<IMG SRC =images/church.jpg>");
}
else if ($picture == "kitten"){
print ("<IMG SRC =images/kitten.jpg>");
}
else if ($picture == "planet"){
print ("<IMG SRC =images/planet.jpg>");
}
else if ($picture == "cartoon"){
print ("<IMG SRC =images/cartoon.jpg>");
}
else if ($picture == "space"){
print ("<IMG SRC =images/stellar.jpg>");
}
else if ($picture == "abstract"){
print ("<IMG SRC =images/abstract.jpg>");
}
else {
print ("No Image to Display");
}
}
?>
</body>
</html>
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 about Conditional logic!
Beginners PHP
–43–
More Conditional Logic
You saw in the last section how to test what is inside of a variable. You used if,
else … if, and else. You used the double equals sign (= =) to test whether the
variable was the same thing as some direct text. The double equals sign is known
as a Comparison Operator. There a few more of these “operands” to get used.
Here’s a list. Take a look, and then we’ll see a few examples of how to use them.
Comparison Operators
Operand Example Meaning
= = $variable1 = = $variable2 Has a value of
Has the same value as
!= $variable1 != $variable2 Does NOT have a value of …
Does NOT have the same value as"
< $variable1 < $variable2 Less than
> $variable1 > $variable2 Greater than
<= $variable1 <= $variable2 Less than or equals to
>= $variable1 >= $variable2 Greater than or equals to
Here’s some more information on the above Operands.
==
The double equals sign can mean “Has a value of” or "Has the same value as”.
In the example below, the variable called $variable1 is being compared to the
variable called $variable2
if ($variable1 = = $variable2) {
}
!=
You can also test if one condition is NOT the same as another. In which case, you
need the exclamation mark/equals sign combination ( != ). If you were testing for a
genuine username, for example, you could say:
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.
Home and Learn
–44–
<
You'll want to test if one value is less than another. Use the left angle bracket for
this ( < )
>
You'll also want to test if one value is greater than another. Use the right angle
bracket for this ( > )
<=
For a little more precision, you can test to see if one variable is less than or equal
to another. Use the left angle bracket followed by the equals sign ( <= )
>=
If you need to test if one variable is greater than or equal to another, use the right
angle bracket followed by the equals sign ( >= )
We’ll now run through a few examples. You’ve already used the double equals
sign, so we’ll start with “NOT equal to”.
NOT Equal To
Create a new PHP file for this, and add the following script:
<?PHP
$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 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
Beginners PHP
–45–
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?
Less Than and Greater Than
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:
<?PHP
$total_spent = 110;
$discount_total = 100;
if ($total_spent > $discount_total) {
print("10 percent discount applies to this order!");
}
?>
By using the great 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 text):
Home and Learn
–46–
<?PHP
$total_spent = 90;
$discount_total = 100;
if ($total_spent > $discount_total) {
print("10 percent discount applies to this order!");
}
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.
Less Than or Equal To and Greater Than or Equal To
We can use the same code above to illustrate "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;
Now run your code again. Did anything print?
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).
Instead of adding yet another else if part, checking to see if the two totals are
equal, we can use <= or >=. Here's how. Change this line in your code:
else if($total_spent < $discount_total) {
to this:
else if($total_spent <= $discount_total) {
Beginners PHP
–47–
(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.
The operands 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, let's take a look at another logic technique
you can use – the Switch Statement.
The Switch Statement
In some earlier code, 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:
<?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.
Home and Learn
–48–
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;
}
It looks a bit complex, so we'll break it down.
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 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 semi 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 at the start of the book. It’s
in the scripts folder. Try out, if you like!
If you look at the last few lines of the Switch Statement, 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.
Beginners PHP
–49–
Logical Operators
As well as the 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.
Operand Example Meaning
&& $variable1 && $variable2 Are both values true?
| | $variable1 || $variable2 Is at least one value true?
AND $variable1 AND $variable2 Are both values true?
XOR $variable1 XOR $variable2 Is at least one value true, but
NOT both?
OR $variable1 OR $variable2 Is at least one value true?
! !$variable1 Is NOT something
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.
The && Operand
The && symbols mean AND. Use this if you need both values to be true, as in our
username and password test. After all, you don't want to let people in if they just
get the username right but not the password! Here's an example:
$username ='user';
$password ='password';
if ($username ='user' &&$password ='password') {
print("Welcome back!");
}
else {
print("Invalid Login Detected");
}
The if statement is set up the same, but notice that now two conditions are being
tested:
$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 | | Operand
Home and Learn
–50–
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';
if ($total_spent =100 || $special_key ='SK12345') {
print("Discount Granted!");
}
else {
print("No discount for you!");
}
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:
$username ='user' &&$password ='password
With this
$username ='user' AND $password ='password
And this:
$total_spent =100 || $special_key ='SK12345'
With this:
$total_spent =100 OR $special_key ='SK12345'
It's up to you which you use. AND is a lot easier to read than &&. OR is a lot
easier to read than ||.
The difference, incidentally, is to do with Operator Precedence. We touched on
this when we discussed variables, earlier. Logical Operators have a pecking order,
as well. The full table is coming soon!
Beginners PHP
–51–
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 = 'best ears';
$contestant_two = 'best teeth';
if ($contestant_one XOR $contestant_two) {
print("Both can't win!");
}
else {
print("Only one winner!");
}
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!
Boolean Values
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;
Home and Learn
–52–
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) {
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 {
print("that's not true");
}
Beginners PHP
–53–
You'll probably meet Boolean values a lot, during your programming life. It's
worth getting the hang of them!
= = = and != =
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';
if ($number === $text) {
print("Same");
}
else {
print("Not the same");
}
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!
Operator Precedence – a List
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:
* / % Highest Precedence
+ - .
< <= > >=
= = = != =
&&
| |
And
XOR
OR Lowest Precedence
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 brief look at HTML forms, and how to get data
from them. This is just an introduction, so that we can do other things besides
printing to the screen.
Home and Learn
–54–
HTML FORMS
In this section, you'll see how to get data from a basic HTML form. Once you can
get values from a form, you'll then see how to test the values you get back. We'll
use Conditional Logic a lot, here, so that you can get more practice with it.
The HTML Form
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>
<FORM NAME ="form1" METHOD =" " ACTION = "">
<INPUT TYPE = "TEXT" VALUE ="username">
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login">
</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!) 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:
Beginners PHP
–55–
Once you get that basic HTML form up and running, we'll see how to get the value
from the text box using PHP.
FORM Attributes
If a user comes to your site and has to login, 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.
Method
If you look at the first line of our form you'll notice a METHOD attribute:
<FORM NAME ="form1" METHOD =" " ACTION = "">
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:
<FORM NAME ="form1" METHOD ="GET" ACTION = "">
To see what effect using GET has, save your work again and then click the Submit
button on your form. You should see this:
Home and Learn
–56–
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. You use the
GET method when the data you want returned is not crucial information that needs
protecting.
Post
The alternative is to use POST. Change the first line of your FORM to this:
<FORM NAME ="form1" METHOD ="POST" ACTION = "">
Close your browser down, and open it back up. Load your basicForm.php page
again, and then click the button. Your address bar will then look like this:
The ?Submit1=Login part 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 POST.
Action
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 change you FORM line to this:
Beginners PHP
–57–
<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!
Submit
The HTML Submit button is used to submit form data to the script mentioned in
the ACTION attribute. Here's ours:
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login">
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.
Using PHP to get values from a HTML form
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.
Getting values from a Text Box
To get the text that a user entered into a textbox, the textbox needs a NAME
attribute. You then tell PHP the NAME of the textbox you want to work with. Our
textbox hasn't got a NAME yet, so change your HTML to this:
<INPUT TYPE = "Text" VALUE ="username" NAME = "username">
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'];
Home and Learn
–58–
You can assign this to a variable:
$Your_Variable = $_POST['formElement_name'];
Before we explain all the syntax, add the following PHP script to the code you
have so far. Make sure to add it the HEAD section of your HTML:
<html>
<head>
<title>A BASIC HTML FORM</title>
<?PHP
$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.
So how does it work?
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'];
Beginners PHP
–59–
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'];
Of course, you need the semi-colon to complete the line.
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.
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") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
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.
Checking if the Submit was clicked
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.
Home and Learn
–60–
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['Submit'])) { }
Now that looks a bit messy! But it actually consists of three parts:
if ( ) { }
isset( )
$_POST['Submit']
You know about the if statement. But in between the round brackets, we have
isset( ). This just 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 to the following and try it out:
if (isset($_POST['Submit'])) {
$username = $_POST['username'];
if ($username == "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
}
The new addition is in bold. Make a note of where all those messy round, square
and curly brackets are. Miss one out and you'll get an error!
Setting the ACTION attribute to a different PHP page
As was mentioned earlier, you don't have to submit your form data to the same
PHP page. You can send it to an entirely different PHP page. To see how it works,
try this:
€‰Chop out your PHP script from the basicForm.php page
€ŠOpen up a new text file and paste it into there
€‹Save your work with the name submitForm.php
Beginners PHP
–61–
€ŒChange the HTML from this:
<Form name="form1" Method ="POST" ACTION ="basicForm.php">
To this
<Form name="form1" Method ="POST" ACTION ="submitForm.php">
The only thing you're changing is the script name, from basicForm.php to
submitForm.php. When the Submit button is clicked, the form data will be
posted to this new PHP script. But you should now have two files:
HTML ONLY - basicForm.php
<html>
<head>
<title>A BASIC HTML FORM</title>
</head>
<body>
<Form name ="form1" Method ="POST" Action ="submitForm.php">
<INPUT TYPE = "TEXT" VALUE ="username" Name ="username">
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login">
</FORM>
</body>
</html>
PHP ONLY - submitForm.php
<?PHP
$username = $_POST['username'];
if ($username == "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
?>
Home and Learn
–62–
In the PHP script, 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.
Keeping the data the user entered
When our 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.
First, put your two files back together again, since we'll only be using one. That
means the PHP should be in the HEAD section of the HTML, as it was before we
asked you to chop it out! In case you've forgotten, the entire script we had was
this:
<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>
Beginners PHP
–63–
If you look at the VALUE attribute of the text box in the HTML above, 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.
To post the details back to the form, and thus keep the data the user has already
typed out, you can use this:
value="<?PHP print $username ; ?>"
In other words, the VALUE attribute is now a PHP line of code. The line of code
is just this:
<?PHP
print $username ;
?>
It's a bit hard to read, because it's all on one line.
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") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
}
else {
$username ="";
}
The new addition is in bold. But in the else statement, 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.
Home and Learn
–64–
However, there are some security issues associated with textboxes (and other form
elements). So we'll see a more secure way to handle these later in the book.
But our new line of HTML for our textbox reads like this:
<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 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.
How to handle other Form Elements with PHP
We'll now take a look at some of the other elements you can have on a HTML
form, and how to return data from these.
Radio Buttons
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:
Beginners PHP
–65–
The HTML code for the above page is as follows:
(You can find the code in the files you downloaded at the start of the book, in the
scripts folder, if you don't fancy typing it all out yourself. The file is called
radioButton.php) Open it up in your text editor.
<html>
<head>
<title>Radio Buttons</title>
</head>
<body>
<Form name ="form1" Method ="Post" ACTION ="radioButton.php">
<Input type = 'Radio' Name ='gender' value= 'male'>Male
<Input type = 'Radio' Name ='gender' value= 'female'>Female
<P>
<Input type = "Submit" Name = "Submit1" Value = "Select a Radio Button">
</FORM>
</body>
</html>
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;
?>
Home and Learn
–66–
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.
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:
The PHP code:
<?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';
}
}
?>
Beginners PHP
–67–
The HTML FORM code:
<FORM name ="form1" method ="post" action ="radioButton.php">
<Input type = 'Radio' Name ='gender' value= 'male'
<?PHP print $male_status; ?>
>Male
<Input type = 'Radio' Name ='gender' value= 'female'
<?PHP print $female_status; ?>
>Female
<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:
<?PHP print $female_status; ?>
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.
First we have two variables at the top of the code:
$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.
Next we have our check to see if Submit is 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:
Home and Learn
–68–
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 tad tricky, when you want
to retain the value of the selected item. Speaking of tricky – checkboxes are up
next!
Checkboxes
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:
Beginners PHP
–69–
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.
Because the code is a little more complex, we've included it in the files you
downloaded at the start of the book. The script you're looking for is
checkboxes.php, and is in the scripts folder. Open it up and take a look at the
code. Here it is in full:
<html>
<head>
<title>Checkboxes</title>
<?PHP
$ch1 = 'unchecked';
$ch2 = 'unchecked';
$ch3 = 'unchecked';
$ch4 = 'unchecked';
$ch5 = 'unchecked';
Home and Learn
–70–
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';
}
}
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';
}
}
}
?>
Beginners PHP
–71–
</head>
<body>
<FORM NAME ="form1" METHOD ="POST" ACTION ="checkBoxes.php">
<Input type = 'Checkbox' Name ='ch1' value ="net"
<?PHP print $ch1; ?>
>Visual Basic .NET
<P>
<Input type = 'Checkbox' Name ='ch2' value="word"
<?PHP print $ch2; ?>
>Microsoft Word
<P>
<Input type = 'Checkbox' Name ='ch3' value="excel"
<?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>
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Choose your books">
</FORM>
</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:
Home and Learn
–72–
$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'])) {
}
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:
<Input type = 'Checkbox' Name ='ch1' value ="net"
<?PHP print $ch1; ?>
>Visual Basic .NET
Beginners PHP
–73–
Again, this is the same code you saw with the Radio Buttons. The PHP part is:
<?PHP print $ch1; ?>
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.
You'll learn more about dealing with HTML forms in a later sections. For now,
we'll leave the subject, and move on. It's a bit of a bumpy ride in the next part,
though, as we're tackling loops!
Home and Learn
–74–
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.
You want to add up the numbers 1 to 4: 1 + 2 + 3 + 4. You could do it like 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;
for($start; $start < 11; $start++) {
$counter = $counter + 1;
print $counter . "<BR>";
}
?>
Beginners PHP
–75–
How did you get on? You should have seen the numbers 1 to 10 printed on your
browser page.
The format for a For Loop is this:
for (start value; end value; update expression) {
}
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
for($start; $start < 11; $start++) {
Or you can assign your loop value right in the For Loop code:
for($start = 1; start < 11; start++) {
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.
for($start; $start < 11; $start++) {
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
Home and Learn
–76–
update our start value, our loop would 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.
A Times Table Programme
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:
Beginners PHP
–77–
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.
Code for the PHP Times Table
The code for the Times Table 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:
Home and Learn
–78–
<?PHP
$times = 2;
if (isset($_POST['Submit1'])) {
$start = $_POST['txtStart'];
$end = $_POST['txtEnd'];
$times = $_POST['txtTimes'];
for($start; $start <= $end; $start++) {
$answer = $start * $times;
print $start . " multiplied by " . $times . " = " . $answer . "<BR>";
}
}
?>
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'];
}
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.
To get the values from the textboxes, we use the following:
$start = $_POST['txtStart'];
$end = $_POST['txtEnd'];
$times = $_POST['txtTimes'];
Beginners PHP
–79–
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:
for($start; $start <= $end; $start++) {
$answer = $start * $times;
}
Let's look at that first line again:
for($start; $start <= $end; $start++) {
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:
$start <= $end
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".
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:
$answer = $start * $times;
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;
Home and Learn
–80–
$answer = 2 * 2;
$answer = 3 * 2;
etc
Finally, we displayed the result to the page like this:
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?
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;
while ($counter < 11) {
print (" counter = " . $counter . "<BR>");
$counter++;
}
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.
Beginners PHP
–81–
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;
while ($counter < 11) {
print (" counter = " . $counter . "<BR>");
//$counter++;
}
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.
$start = 1;
$times = 2;
$answer = 0;
while ($start < 11) {
$answer = $start * $times;
print ($start . " times " . $times . " = " . $answer . "<BR>");
$start++;
}
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!
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)
Home and Learn
–82–
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.
The 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;
while ($counter < 11) {
print(" counter = " + $counter + "<BR>");
if ($TeacherInterrupts == true) break;
$counter++;
}
Try the code out and see what happens.
For Each
This type a loop is a special loop. It's quite useful for things called arrays, which
you'll study next. You'll see this type of loop soon!
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!)
Beginners PHP
–83–
Arrays
Arrays are another of those things that help enormously when you're
programming. Bu t like loops, they can be quite difficult to master, when you're
first starting out. In this section, you'll see just what they are, and how to set up
your own arrays
What is an Array?
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:
$Order_Number1 = "Black shoes";
$Order_Number2 = "Tan shoes";
$Order_Number3 = "Red shoes";
$Order_Number4 = "Blue shoes";
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.
Setting up an Array
In the code above, 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:
Home and Learn
–84–
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.
Method One – Type between the round brackets
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:
$seasons = array("Autumn", "Winter", "Spring", "Summer");
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:
("Autumn", "Winter", "Spring", "Summer")
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");
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"
Beginners PHP
–85–
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.
$Array_Name = array(10, 20, 30, 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);
This array will then look like this:
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.
You can store text and numbers in the same array:
$Array_Name = array(1 => 10, 2 => "Spring", 3 => 30,
4 => "Summer");
The above array would then look like this:
1=> 10,
2=> "Spring",
3=> 30,
4=> "Summer"
Home and Learn
–86–
Method two – Assign values to an array
Another way to put values into an array is like this:
$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";
PHP will then see your array like this:
1=> "Autumn",
2=> "Winter",
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;
Beginners PHP
–87–
$answer = array();
for ($start; $start < 11; $start++) {
$answer[$start] = $start * $times;
}
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!
Getting at the values stored in your arrays
OK, so you now know how to store values in your array (with method one or
method two). 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
$seasons = array("Autumn", "Winter", "Spring", "Summer");
print $seasons[0];
?>
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];
You can also assign this value to another variable:
$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:
$seasons = array("Autumn", "Winter", "Spring", "Summer");
print $seasons[0];
print $seasons[1];
print $seasons[2];
print $seasons[3];
Home and Learn
–88–
Or you could do it like this:
for ($key_Number = 0; $key_Number < 4; $key_Number++) {
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!
Array - Using Text as Keys
Your arrays keys don't have to be numbers. 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:
David => "Gilmour",
Nick => "Mason",
Roger => "Waters",
Richard => "Wright"
This is easier to remember than this:
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"];
Beginners PHP
–89–
Arrays and For Each
However, because Associative arrays don't have numbers for the keys, another
technique is used to loop round them – the For Each loop. Here's one in action:
$full_name = array();
$full_name["David"] = "Gilmour";
$full_name["Nick"] = "Mason";
$full_name["Roger"] = "Waters";
$full_name["Richard"] = "Wright";
foreach ($full_name as $key_name => $key_value) {
print "Key = " . $key_name . " Value = " . $key_value . "<BR>";
}
This type of 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:
foreach ($full_name as $key_name => $key_value) {
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:
$full_name as $key_name => $key_value
You start by typing the name of the array you want to loop round. For us, that was
$full_name. Next is this:
as $key_name => $key_value
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:
foreach ($full_name as $first_name => $surname) {
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.
Home and Learn
–90–
If you need to access values from an Associative array, then, use a foreach loop.
Before we give you some examples to try out, here's a few useful things you can
do with arrays.
Sorting 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];
Beginners PHP
–91–
The numbers are then sorted from lowest to highest. If you want to sort in reverse
order then you need the following:
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
Random Keys 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
$numbers = array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6);
$random_key = array_rand($numbers, 1);
print $random_key;
?>
The function that returns the random key is this:
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.
The count function
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:
$seasons = array("Autumn", "Winter", "Spring", "Summer");
$array_count = count($seasons);
for ($key_Number = 0; $key_Number < $array_count; $key_Number++) {
print $seasons[$key_Number];
}
To get how many elements are in the array, we used this:
Home and Learn
–92–
$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:
for ($key_Number = 0; $key_Number < $array_count; $key_Number++)
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 chapter on arrays, here a few script for you to try out. The scripts
are amongst the files you downloaded at the start of the book (in the scripts
folder), if you want to copy and paste them. The file you're looking for is called
scripts.txt.
Script One - Set up an array and print out the values
<?PHP
$seasons = array("Autumn", "Winter", "Spring", "Summer");
print $seasons[0] . " ";
print $seasons[1] . " ";
print $seasons[2] . " ";
print $seasons[3];
?>
Script Two - Set up an array with your own Keys
<?PHP
$seasons = array(1 => "Autumn", 2 => "Winter", 3 => "Spring", 4 => "Summer");
print $seasons[1] . " ";
print $seasons[2] . " ";
print $seasons[3] . " ";
print $seasons[4];
?>
Beginners PHP
–93–
Script Three - Set up an array with mixed values
<?PHP
$seasons = array(1 => 10, 2 => "Spring", 3 => 30, 4 => "Summer");
print $seasons[1] . " ";
print $seasons[2] . " ";
print $seasons[3] . " ";
print $seasons[4];
?>
Script four - Assign values to an array: Method Two example
<?PHP
$seasons = array();
$seasons[]="Autumn";
$seasons[]="Winter";
$seasons[]="Spring";
$seasons[]="Summer";
print $seasons[0] . " ";
print $seasons[1] . " ";
print $seasons[2] . " ";
print $seasons[3];
?>
Script Five - Looping round values in an array
<?PHP
$start = 1;
$times = 2;
$answer = array();
for ($start; $start < 11; $start++) {
$answer[$start] = $start * $times;
}
Home and Learn
–94–
print $answer[1] . " ";
print $answer[4] . " ";
print $answer[8] . " ";
print $answer[10];
?>
Script Six - Looping round values in an array: example 2
<?PHP
$seasons = array("Autumn", "Winter", "Spring", "Summer");
for ($key_Number = 0; $key_Number < 4; $key_Number++) {
print $seasons[$key_Number];
}
?>
Script Seven - Using text as Keys
<?PHP
$full_name = array();
$full_name["David"] = "Gilmour";
$full_name["Nick"] = "Mason";
$full_name["Roger"] = "Waters";
$full_name["Richard"] = "Wright";
print $full_name["Nick"] . "<BR>";
print $full_name["David"];
?>
Script Eight - Looping round an Associative array using For
Each
<?PHP
$full_name = array();
$full_name["David"] = "Gilmour";
$full_name["Nick"] = "Mason";
$full_name["Roger"] = "Waters";
Beginners PHP
–95–
$full_name["Richard"] = "Wright";
foreach ($full_name as $first_name => $surname) {
print "Key = " . $first_name . " Value = " . $surname . "<BR>";
}
?>
Script Nine - Sorting Arrays (Associative)
<?PHP
$full_name = array();
$full_name["Roger"] = "Waters";
$full_name["Richard"] = "Wright";
$full_name["Nick"] = "Mason";
$full_name["David"] = "Gilmour";
foreach ($full_name as $first_name => $surname) {
print "Key = " . $first_name . " Value = " . $surname . "<BR>";
}
print "<P>";
ksort($full_name);
foreach ($full_name as $first_name => $surname) {
print "Key = " . $first_name . " Value = " . $surname . "<BR>";
}
?>
Script Ten - Sorting Arrays (Scalar)
<?PHP
$numbers = array();
$numbers[]="2";
$numbers[]="8";
$numbers[]="10";
Home and Learn
–96–
$numbers[]="6";
print $numbers[0] . " ";
print $numbers[1] . " ";
print $numbers[2] . " ";
print $numbers[3];
?>
Arrays are an important programming technique, and they help your coding
enormously, once you master them.
In the next section, we'll take a look at another important area for you to work on -
string techniques.
Beginners PHP
–97–
String Manipulation
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.
Changing Case
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.
<?PHP
$full_name = 'bill gates';
if (isset($_POST['Submit1'])) {
$full_name = $_POST['username'];
$full_name = ucwords($full_name);
}
?>
Home and Learn
–98–
The first line just makes sure that the lowercase version is placed into the textbox
when the page loads:
$full_name = 'bill gates';
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:
$full_name = ucwords($full_name);
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:
$full_ sentence = ucfirst($full_ sentence);
To convert all the letters to either upper or lowercase, use these:
strtoupper( )
strtolower( )
Here's an example of how to use them:
$change_to_lowercase = "CHANGE THIS";
$change_to_lowercase = strtolower($change_to_lowercase);
$change_to_uppercase = "change this";
$change_to_uppercase = strtoupper($change_to_lowercase);
Again, the variable or text you want to change goes between the round brackets of
the function. This is then assigned to a variable.
Trimming White Space
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 PGP functions to help you
do this:
Beginners PHP
–99–
Suppose your user has entered this in the textbox:
" username "
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
$space = " username ";
$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
$space = trim(" username ");
$letCount = strlen($space);
print $letCount;
?>
When you run the script now, you should find that the variable has the correct
number of characters - 8.
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.
Shuffle characters
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:
Home and Learn
–100–
<?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.
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;
If you try it with the Firefox browser, you'd get something like this:
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.7.5)
Gecko/20041110 Firefox/1.0
However, Internet Explorer returns something like this:
Mozilla/4.0 (compatible; MSIE6.0; Windows NT 5.1; SV1;
.NET CLR 1.1.4322; .NET CLR 2.0.50215)
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:
strpos(string_to_search, string_to_find, start)
You need to supply at least the first two. The third, start, is optional. Here's a
simple example.
$full_name = "bill gates";
$letter_position = strpos($full_name, "b");
print $letter_position;
Beginners PHP
–101–
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.
Try changing strpos() from this:
$letter_position = strpos($full_name, "b");
To this:
$letter_position = strpos($full_name, "B");
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.
$full_name = "bill gates";
$letter_position = strpos($full_name, "B");
if ($letter_position === false) {
print "Character not found " ;
}
else {
print "Character found";
}
The triple equals operator ( = = =) not only checks for a value, remember, 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 = = =.
Here's a script that checks which of four browsers the user has:
$agent = $_SERVER['HTTP_USER_AGENT'];
if ( strpos(strtoupper($agent), 'MSIE')) {
print "Internet Explorer";
}
else if (strpos(strtoupper($agent), 'FIREFOX')) {
print "Firefox";
}
else if (strpos(strtoupper($agent), 'KONQUEROR')) {
print "Konqueror";
Home and Learn
–102–
}
else if (strpos(strtoupper($agent), "LYNX")) {
print "Lynx";
}
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!
Splitting a line of text
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:
Poll number 1, 1500, 250, 150, 100, 1000
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:
$text_line = "Poll number 1, 1500, 250, 150, 100, 1000";
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
Beginners PHP
–103–
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:
explode(separator, string_to_split)
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:
$text_line = "Poll number 1, 1500, 250, 150, 100, 1000";
$text_line = explode("," , $text_line);
So we're saying, "Look for a comma in the text, and split the line of text into
separate pieces." Once PHP does its job, it puts all the parts into the variable on
the left hand side of the equals sign ( = ), which was $text_line for us. This
variable will then be an array!
To get at the pieces of the array, access it in the normal manner. Here's some code
to try:
<?PHP
$text_line = "Poll number 1, 1500, 250, 150, 100, 1000";
$text_line = explode(",",$text_line);
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);
Run your code and see what happens.
Home and Learn
–104–
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:
$text_line = "Poll number 1, 1500, 250, 150, 100, 1000";
$text_line = explode(",",$text_line);
for ($start=0; $start < count($text_line); $start++) {
print $text_line[$start] . "<BR>";
}
In the for loop above, we set a start value to zero. The end condition is this:
$start < count($text_line)
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).
Inside the loop, we have a normal print statement:
print $text_line[$start] . "<BR>";
To get at each element in the array, this is used:
$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.
Joining text into a single line
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( ):
$seasons = array("Autumn", "Winter", "Spring", "Summer");
$new_textline = implode(",", $seasons)
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( ).
Beginners PHP
–105–
implode(separator, text_to_join)
So implode( ) will join all the text together and separate each part with a comma,
in the code above. Of course, you don't have to use a comma. You could use a
dash:
$new_textline = implode("-", $seasons)
Or any other character:
$new_textline = implode("#", $seasons)
Even a space:
$new_textline = implode(" ", $seasons)
The implode( ) function can come in handy, if you need to work with single lines
of text.
PHP and Escaping
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
$string = 'John's Car';
print $string;
?>
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:
$string = "John's Car";
Or you could escape the apostrophe. You escape a character by typing a "slash"
before it. Like this:
$string = 'John\'s Car';
Home and Learn
–106–
If you try that out, you should find that the string prints correctly.
Now try this script:
<?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.
String function list
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:
http://www.w3schools.com/php/func_string_chr.asp,
http://www.zend.com/manual/ref.strings.php
Here's our list, though. Click on a link to go to that string function.
Beginners PHP
–107–
String Function Explanation
chr( ) Converts an ASCII value to a its equivalent character.
ord( ) Find out what the ASCII value of a character is.
echo( ) Can be used an alternative to the print statement.
similar_text( ) Tells you how similar two strings of text are.
str_repeat( ) Repeats a character a specified number of times.
str_replace( ) Replace one string with another.
str_word_count( ) Tells you how many words a string has.
strlen( ) Gets the length of a string.
substr( ) Grab a number of character from a string.
chr( )
Converts an ASCII value to its equivalent character. For example, the ASCII value
64 is the @ symbol on a UK keyboard. If you want to disguise your email address,
you could do it like this:
$email_address = "me" . chr(64) . "me.com";
print $email_address;
ord( )
Find out what the ASCII value of a character is with this string function. To see
what ASCII value the @ symbol returns, you can use it like this:
$ascii_num = ord("@");
print $ascii_num
echo( )
Can be used as an alternative to the print statement. These do the same thing:
$display_data = "something to display";
print $display_data;
echo $display_data;
similar_text( )
As it's name suggests, tells you how similar two strings of text are. The syntax is:
similar_text($string1, $string2, $percent)
Home and Learn
–108–
The first two are the strings you want to compare. The percent tells you how
accurate, in percentage terms, the match was. This is optional, though, so you can
leave it out. Here's an example that tells the user how accurately they entered a
username:
$real_username ="Bill Gates";
$user_attempt = "Bill Bates";
$check = similar_text($real_username, $user_attempt, $percent);
print($check) . "<BR>";
print($percent . "% correct");
The above script will print out the following:
9
90% correct
The blank space is counted as a character.
str_repeat( )
Repeats a character a specified number of times. If you want nine dollar signs, for
example, then you'd use the function like this:
$extra_dollars = str_repeat("$", 9);
print $extra_dollars;
str_replace( )
This allows you to replace one string with another. The syntaxt is:
str_replace($look_for, $change_to, $search_text, match_count);
The last one, match_count, is optional. It's counts how many matches it has
found.
In the example below, we're looking for "explore" and want to replace it with
"explode".
$search_text = "The explore function";
$look_for = "explore";
$change_to = "explode";
print $search_text . "<BR>";
$changed_text = str_replace($look_for, $change_to, $search_text);
print $changed_text;
Beginners PHP
–109–
So you're looking for one string in the search text, and replacing it with another.
str_word_count( )
Tells you how many words a string has. The syntax is this:
str_word_count(string, return ,char)
If all you want to know is how many words a string has, then you can leave out
"return", and "char". In which case, you can use it like this:
$num_of_words = str_word_count("The explore function");
print $num_of_words;
The return value can be one of three numbers:
0 - How many words found. This is the default
1 - Brings the string back as an array.
2 - Brings the string back as an array, but the Keys change based on where
in the string the words are found. Might be useful to someone!
strlen( )
Gets the length of a string. The length is how many characters in the string:
$string_length = strlen("This is some text");
The above line of code returns a value of 17 – the number of character and spaces
in the string.
substr( )
This function is short for Substring. You can grab a number of character from a
string with substr( ). For example, suppose you wanted to check if an email
address ended in .com. You could grab the last few characters and check them
with an if statement. The syntax for substr( ) is this:
substr(string, start, length)
So you provide the function with a string, then you have to tell PHP which
character in the string to start at. The length is how many characters you want to
grab. This is optional. If you miss it out, you'll grab all the characters to the end of
the string.
Here's an example that checks an email address to see if ends in .com.
Home and Learn
–110–
$email = "test@test.com";
$email_end = substr($email, strlen($email) - 4);
if ($email_end == ".com" ) {
print "ends in .com";
}
else {
print "doesn't end in .com";
}
Run the script and see which one prints out!
You can also start the search from the end of the string. In which case, provide a
negative number. Try this new substr( ) line, in place of the one above:
$email_end = substr($email, -4, 4);
This time, we have a figure of minus four. This means "start 4 characters from the
left of the end of the string. There's also a length number specified. This means
"grab four characters from your starting position.
We'll look at some more string function in later section (date and time functions,
and functions you can use for security purposes). But for now, let's take a closer
look at what functions are, and how you can create your own in PHP.
Beginners PHP
–111–
PHP Functions
You've been working with string functions in the last section, and references to
functions have been made in other section. 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.
Suppose you need to check text from a textbox. You want to trim any blank spaces
from the left and right of the text that the user entered. So if they entered this:
" Bill Gates "
You want to turn it into this:
"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:
$user_text = trim($_POST['text1'] );
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 == "") {
error_message = "Blank textbox detected";
}
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!
Home and Learn
–112–
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( ) {
print "Error Detetceted";
}
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( ) {
print "Error Detetceted";
}
?>
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( ) {
print "Error Detetceted";
}
display_error_message( );
?>
Beginners PHP
–113–
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( ) {
print "Error Detetceted";
}
?>
If you have PHP 4 or above, 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).
Variable scope and functions
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
$error_text = "Error Detetceted";
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".
Likewise, try this script:
Home and Learn
–114–
<?PHP
display_error_message();
print $error_text;
function display_error_message() {
$error_text = "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() {
$error_text = "Error message";
print $error_text;
}
?>
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.
Functions and arguments
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 the above script again:
<?PHP
$error_text = "Error message";
display_error_message($error_text);
function display_error_message($error_text) {
print $error_text;
}
?>
Beginners PHP
–115–
Notice our function now:
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. The argument is a single variable that you want your function to
deal with.
Now notice how the function is called:
$error_text = "Error message";
display_error_message($error_text);
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:
$error_text = "Error message";
display_error_message( );
You'll get an error message from PHP something like this:
"Warning: Missing argument 1 for display_error_message()"
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.
So, to recap:
ۥTo pass something to a function, create an argument
€ŽTo call a function that has an argument, don't leave the round brackets
empty
Home and Learn
–116–
A Function to check for blank Textboxes
If you remember the script that we wanted to create earlier it was this:
1. Get the text that a user entered in a textbox on a form
2. Trim any blank spaces from the left and right of the text
3. Check that what you have left is not a blank string
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:
<?PHP
$user_text = trim("Bill Gates");
display_error_message($user_text);
function display_error_message($user_text) {
if ($user_text == "") {
print "Blank text box detected";
}
else {
print "Text OK";
}
}
?>
Try it out. When you run the script, you should find that Text OK prints. Now
change this line:
$user_text = trim("Bill Gates");
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.
Beginners PHP
–117–
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php
$first ="";
$second = "";
function display_error_message($user_text) {
if ($user_text == "") {
print "One or more blank text boxes detected";
}
else {
print "Text boxes OK";
}
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$first = trim($_POST['first']);
$second = trim($_POST['second']);
display_error_message($first);
display_error_message($second);
}
?>
</body>
<FORM Method = "POST" action ="formFunction.php">
First Name: <INPUT TYPE = "text" name = "first" value ="<?=$first?>">
Surnmae: <INPUT TYPE = "text" name = "second" value
="<?=$second?>">
<input type="submit" name="Submit" value="Submit">
</FORM>
</html>
Home and Learn
–118–
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.
Getting values 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:
print ("Get on with it!");
$string_length = strlen($string_length);
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;
if ($total_spent > 100) {
$discount_total = $total_spent - ($total_spent * $discount);
$total_charged = $discount_total;
}
else {
$total_charged = $total_spent;
}
return $total_charged;
}
?>
Beginners PHP
–119–
The lines to concentrate on are the coloured lines. 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;
The next line is our function call:
$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 coloured line at the end:
function calculate_total($total_spent) {
$discount = 0.1;
if ($total_spent > 100) {
$discount_total = $total_spent - ($total_spent * $discount);
$total_charged = $discount_total;
}
else {
$total_charged = $total_spent;
}
return $total_charged;
}
The last line is:
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 function called calculate_total( ) to whatever is
stored in the variable we've called $total_charged. It's this that will get stored in
our variable called $order_total.
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.
Home and Learn
–120–
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.
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
$Variable_Value = 10;
example($Variable_Value);
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:
Beginners PHP
–121–
<?php
$Variable_Value = 10;
print "Before the function call = " . $Variable_Value . "<BR>";
example($Variable_Value);
print "After the function call = " . $Variable_Value;
function example($Variable_Value) {
$Variable_Value = $Variable_Value + 10;
print "Inside of the function = " . $Variable_Value . "<BR>";
}
?>
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:
Before the function call = 10
Inside of the function = 20
After the function call = 10
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.
When you hand a function a copy of a variable, it's called passing the variable by
value (just a copy). The alternative is to NOT pass a copy, but to refer back to the
original. Make one small change to your script. This:
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:
Before the function call = 10
Inside of the function = 20
After the function call = 20
Home and Learn
–122–
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!
To wrap up this introduction to functions, here's some useful inbuilt ones available
to you. The last of these is VERY useful!
PHP Server Variables
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'];
print "Referrer = " . $referrer . "<BR>";
print "Browser = " . $browser . "<BR>";
print "IP Adress = " . $ipAddress;
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.)
So to get at the values in Server Variables, the syntax is this:
$_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:
Beginners PHP
–123–
<?PHP
foreach($_SERVER as $key_name => $key_value) {
print $key_name . " = " . $key_value . "<br>";
}
?>
What the script does is to loop round all the server variables and print out the keys
and values in the SERVER array.
HTTP Header() Function
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 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."
INCLUDE( )
Been 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.
Home and Learn
–124–
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.
Now take a look at the code for the PHP page:
<HTML>
<HEAD>
<TITLE>Include files</TITLE>
</HEAD>
<BODY>
<H3>Normal text here </H3>
Normal text written in a HTML Editor
<H3>Include File here</H3>
<?PHP include "textfile.txt" ; ?>
</ BODY>
</ HTML >
Here the PHP code:
<?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:
Beginners PHP
–125–
Suppose you decide to add a new section to your site. The new page should be like
this:
If your site contains lots of pages, that would mean having to amend the HTML of
all of them. A painful and dreaded task! Instead, use the include( ) function.
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:
<?PHP include "linksPage.txt" ?>
Home and Learn
–126–
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 height="30" valign="middle" bgcolor="#FFFFCC">
<a href="links.php">New Section</a>
</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 at the start of the book). The code is quite simple. It's just
this:
<?PHP
include "myOtherScript.php";
print "This was printed from the includeScript.php";
print "<BR>";
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() {
print "This was printed from the myOtherScript.php";
}
?>
Beginners PHP
–127–
Load up the page called includeScript.php in your browser. You should see two
lines printed out.
So, the 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!
Home and Learn
–128–
Security Issues and Form Elements
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:
<html>
<head>
<title>Test Attack</title>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$first_name = $_POST['first_name'];
echo $first_name;
}
?>
</head>
<BODY>
</body>
<Form Method = "Post" action ="testSecurity.php">
<input type = "text" name = "first_name" value ="test name">
<input type="submit" name="Submit" value="Submit">
</Form>
</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>
Beginners PHP
–129–
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!
Another thing someone could do, especially if you have a forum, is to enter HTML
directly into your textboxes. They could flood your forum with links to harmful or
undesirable web sites. Try this as example. Delete everything from your textbox,
and enter this:
<A HREF ="nastysite">A Nasty Site</A>
When you click Submit this time, you should see the following:
Home and Learn
–130–
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.
htmlspecialchars()
You can use the inbuilt PHP function htmlspecialchars( ) to convert certain
HTML into their respective symbols. 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:
<A HREF ="nastysite">A Nasty Site</A>
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:
&lt;
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 this,
$first_name = $_POST['first_name'];
echo $first_name;
To this:
$first_name = $_POST['first_name'];
$first_name = htmlspecialchars($first_name);
echo $first_name;
The new line is in second from the bottom. Run your code again, and see what
happens. You should see this display in the browser:
Beginners PHP
–131–
Now it's not treating the hyperlink as HTML – it's turning it into plain text.
The new line in the script is this:
$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.
Home and Learn
–132–
strip_tags( )
A third option is to use the strip_tags( ) function. 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:
strip_tags($string, html_tags_to_ignore)
So the first thing you need to provide the strip_tags( ) function with is the string
of text you're trying to check. The second thing, html_tags_to_ignore, is optional.
If you leave this off then the function will strip all tags. Here's two example to try:
$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;
Beginners PHP
–133–
So the HTML you want to include goes after a comma, and between quote marks.
In the code above, we're allowing the HTML bold tag through. Here's what the
text area, and the result looks like:
Before clicking Submit
After clicking Submit
So the HTML in the first picture has been allowed through. In the second picture,
you can see that the text is now in bold.
Home and Learn
–134–
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.
Beginners PHP
–135–
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.
Opening a file
There is text file amongst the ones you downloaded at the start of the book called
dictionary.txt (in the scripts folder). Open this file up, and take a look at the
contents.
It should look like this:
AAS = Alive and smiling
ADN = Any day now
AEAP = As early as possible
AFAIK = As far as I know
AFK = Away from keyboard
AKA = Also known as
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.
readfile(file_to_read)
To open up a file, there 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.
<?PHP
$file_contents =readfile("dictionary.txt");
print $file_contents;
?>
Home and Learn
–136–
Save the script with any file name your like, but make sure it goes in the same
folder as your new PHP script. 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");
But here's the part that does the reading.
$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);
Or have any other file reference you want to use.
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( ).
Beginners PHP
–137–
fopen(file_to_open)
A better method to open files is with fopen( ). This function gives you more
options, such as setting whether the file is for reading only, for writing to as well,
and a few more options. Here's an example:
<?PHP
$file_contents = fopen("dictionary.txt", "r");
print $file_contents;
fclose($file_contents);
?>
Run this script and see what happens. You should see something like the following
printed out:
Resource id #2
Not quite what you were expecting! The reason is that fopen( ) doesn't actually
read the contents of a file. All it does is to set a pointer to the file you want to
open. It then returns what's call a file handle. All you're doing is telling PHP to
remember the location of the file.
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(). Try the script out, then we'll explain what's
happening:
<?PHP
$file_handle = fopen("dictionary.txt", "r");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
print $line_of_text . "<BR>";
}
fclose($file_handle);
?>
Home and Learn
–138–
What you should find is that the contents are printed out on separate lines. But
how does it work?
The first line is this:
$file_handle = fopen("dictionary.txt", "r");
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.
The next line is tricky! It's a while loop:
while (!feof($file_handle) ) {
}
There's really two parts to this. There's the while loop:
while ( ) {
}
And then there's the condition for the while loop:
!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:
while (!feof($file_handle) ) {
}
Beginners PHP
–139–
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.
Inside the while loop, the first line is this:
$line_of_text = fgets($file_handle);
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:
print $line_of_text . "<BR>";
As well as printing out the line of text, we're adding a HTML line break.
The last line in the code is this:
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.
Home and Learn
–140–
Options for fopen( )
In the code above, we're only reading the file. This was why we had the letter "r"
in the round brackets of fopen( ):
$file_handle = fopen("dictionary.txt", "r");
But there are other options. Here's a fuller list of things you can replace "r" with.
Mode Meaning
r Use this to read a file only. The pointer is set to the start of the file.
r+ Use this to read and write to a file. The pointer is set to the start of
the file.
w Use this to write to a file only. It will erase the entire contents of the
file you have open. If no file exists with your chosen name, then it
will create one for you
w+ Same as "w", but used to read and write.
a Use this to write to a file only, and append data to the end of the file.
Doesn't erase contents, in other words.
a+ Same as "a", but with read access as well.
x Create a file to write only. But gives you a special warning called
E_WARNING.
x+ Same as x but with read access as well.
t In Windows, a line break is \r\n. The t converts \n line breaks
created on other Operating Systems so that they are readable with
Windows
b Force PHP to open the file in binary mode.
So if you wanted to read and write to the file, you'd use this:
$file_handle = fopen("dictionary.txt", "r+");
Or this, if you want to append data to the end of file when you're writing it back:
$file_handle = fopen("dictionary.txt", "a+");
If you need to work with binary files (like images), then you can add the "b":
$file_handle = fopen("dictionary.txt", "rb");
Beginners PHP
–141–
Checking if the file exists
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")) {
print "file exists";
}
else {
print "file doesn't exist";
}
In between the round brackets of file_exists( ) you type then 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.
Writing to files
When you need to write to files, there are some more functions you need to use. If
you have a version of PHP below version 5, then you can use the fwrite()
function. But you first need to use fopen( ) 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
$file_handle = fopen("testFile.txt", "w");
$file_contents = "Some test text";
fwrite($file_handle, $file_contents);
fclose($file_handle);
print "file created and written to";
?>
The new line is the coloured one. First we ask PHP to open the file and create a
file handle:
$file_handle = fopen("testFile.txt", "w");
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
Home and Learn
–142–
this name. After a comma, we've typed "w". This tells PHP that the file will be
write only.
The third line is where we write to the file:
fwrite($file_handle, $file_contents);
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 "w" into "a". Run your script a few times, then open the text file. What
did you notice?
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()
If you have PHP 5, you can use the new function file_put_contents( ) instead of
fwrite( ).
It is used in the same way, but has an optional third parameter:
file_put_contents($file_handle, $file_contents, context);
The context option can be FILE_USE_INCLUDE_PATH, FILE_APPEND,
LOCK_EX.
So to append to the file, just do this:
file_put_contents($file_handle, $file_contents, FILE_APPEND);
Beginners PHP
–143–
Working with Comma delimited files (CSV 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.
And here's what the data looks like in a text editor.
Home and Learn
–144–
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:
<?PHP
$file_handle = fopen("widgets.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
print $line_of_text[0] . $line_of_text[1]. $line_of_text[2] . "<BR>";
}
fclose($file_handle);
?>
When you run the script, you should see all the lines of text printed out. Here's
how it works.
Beginners PHP
–145–
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.
$file_handle = fopen("widgets.csv", "r");
while (!feof($file_handle) ) {
}
Inside the while loop, though, we have our fgetcsv line:
$line_of_text = fgetcsv($file_handle, 1024);
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:
Widget1, blue, £10
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:
$line_of_text[0]
$line_of_text[1]
$line_of_text[2]
To print it all out, we had a this line:
print $line_of_text[0] . $line_of_text[1]. $line_of_text[2] . "<BR>";
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!
Reading a text file line by line into an array – other options
There is another option you can use to place lines of text into an array. In the
technique below, we're using the explode( ) string function to create an array from
each line of text. Here's the code:
Home and Learn
–146–
<?PHP
$file_handle = fopen("dictionary.txt", "rb");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode('=', $line_of_text);
print $parts[0] . $parts[1]. "<BR>";
}
fclose($file_handle);
?>
The first line to note is this:
$parts = explode('=', $line_of_text);
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:
AAS = Alive and smiling
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.
We then print out both parts of the array with this:
print $parts[0] . $parts[1]. "<BR>";
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.
Beginners PHP
–147–
File Locations
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.
Get the Absolute Path of a File
<?PHP
$absolute_path = realpath("fileDir.php");
print "Absolute path is: " . $absolute_path;
?>
To get the exact path of file, then, you can use realpath(). In between the round
brackets of the function, type the name of the file.
Get the Directory, but not the file name
<?PHP
$dir = dirname("folder/myphp/fileDir.php");
print "directory is: " . $dir . "<BR>";
?>
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.
Get the Filename only
<?php
$bas = basename("folder/myphp/fileDir.php");
print "File Name is: " . $bas . "<BR>";
?>
Home and Learn
–148–
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 a few security implication when working with files.
For a more in-depth discussion on this, and other security issues, these links are
quite useful (though we can’t guarantee that the links are still alive!):
ۥhttp://www.developer.com/lang/article.php/918141
ۥhttp://www.ilovejackdaniels.com/security/writing-secure-php/3/
€‘http://www.sklar.com/page/article/owasp-top-ten
€’http://www.devshed.com/c/a/PHP/PHP-Security-Mistakes/
€“http://www.onlamp.com/pub/a/php/2003/07/31/php_foundations.html
Beginners PHP
–149–
Working with Date and Time functions in PHP
Knowing how to handle date and time values in PHP will be a useful addition to
your programming skills. In this section, we'll take a look at how to process this
type of data.
The date( ) function
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, then the month, then the year. 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 7
th
of April
in the USA. In the UK, it means the 4
th
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:
$today = date('d m y');
Or even this:
$today = date('d~m~y');
Home and Learn
–150–
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.
Here, then, is a fuller list of the date and time characters. They are all case
sensitive.
Day of the week Characters
Character Meaning Example
d
Day of the month 05, 09, 14, 31
D
The day in text format Mon, Wed, Sun
j
Like 'd', but without the zeros 5, 9, 14, 31
l (lowercase 'L')
Like 'D' but not shortened Monday, Sunday
S
Ordinal ending for the day of the month 1
st
, 2
nd
, 20
th
w
Numeric value for day of week 0 is Sunday; 6 is Saturday
W
Week number of the year 12
th
day of the year
z
Numeric day of the year 0 to 365
NOTE: Wis available in PHP version 4.1.0 and above
Month Characters
Character Meaning Example
F Full text format of the month March, April
m Numeric version of the month 01, 05, 10,
M Short text version of the month Jan, Feb, Dec
n Like 'm' but without zeros 1, 5, 10
t Number of days in a given month 28, 29, 30 or 31
Year Characters
Character Meaning Example
L Is it a Leap Year? 1 if yes; 0 if no
y 4 digit year value 2006, 2007
Y 2 digit year value 06, 07
Time Characters
Beginners PHP
–151–
Character Meaning Example
a Morning or Afternoon? am or pm
A Like 'a' but uppercase AM or PM
g 12 hour format – no leading zeros 1, 9, 12
G 24 hour format – no leading zeros 0, 15, 23
h 12 hour format – with zeros 01, 09, 12
H
24 HOUR FORMAT – WITH ZEROS
00, 09, 23
i minutes 00 to 59
s seconds 00 to 59
Other Date and Time Characters
Character Meaning Example
O Greenwich Meantime offset +0300
T Time zone of the computer GMT, EST
r Full formatted date and time using
RFC 2822
Tue, 28 Feb 2006
15:22:23 +0300
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.
Example 1 (prints out something like Monday 7
th
September 2006)
<?PHP
$today = date('l jS F Y');
print $today;
?>
Example 2 (prints out something like "It's week 9 of 2006")
<?PHP
$today = date('W');
$year = date('Y');
print "It's week " . $today . " of " . $year;
?>
Example 3 (prints out something like "11:25:44 am")
Home and Learn
–152–
<?PHP
$time = date('h:i:s a');
print $time;
?>
Example 4 (prints out something like "23:28 GMT Standard Time")
<?PHP
$time = date('G:i T');
print $time;
?>
getdate( )
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:
Beginners PHP
–153–
$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');
If you look at the previous tables, you'll see that "z" means the year day as a
number. So a value of 60 would mean the 60
th
day of the year.
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();
$day_difference = $today['yday'] - $post_date;
Print "Days since last post = " . $day_difference;
?>
So we've set up the array using getdate:
$today = getdate();
We've then used "yday" to calculate how many days have elapsed since the last
post:
$day_difference = $today['yday'] - $post_date;
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
Home and Learn
–154–
PHP and MySQL
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 EasyPHP software you may have installed at the start
of the course. We will be working with MySQL databases throughout these
lessons.
If you installed EasyPHP, then you should see a folder like this on your hard drive:
If you can see all those files and folder then you already have MySQL installed.
If you haven't yet got MySQL, you can download it here:
http://dev.mysql.com/downloads/
Beginners PHP
–155–
Click on the Community Edition link, and you'll be taken to a download page.
Select your operating system from the list. (Windows user might want to try the
Windows (x86) option. This is a setup.exe file that you just double click to install.)
For instructions on how to install MySQL on your operating system, see the online
documentation at http://dev.mysql.com/doc/refman/4.1/en/index.html.
We'll assume that you already have MySQL installed. But to check that it's up and
running using EasyPHP, if you have it (Windows users only), start EasyPHP and
you should see a dialogue box like this:
If you have a green light to the right of the MySQL button, then you database
system is up and running OK.
Now enter this in your browser's address bar:
http://127.0.0.1/mysql/
If it doesn't work, try this:
http://127.0.0.1/home/mysql/
You should see the phpMyAdmin page display:
Home and Learn
–156–
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.
Creating a database using 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.
What is a database and what do they look like?
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.
When you create a database, you're creating a structure like this:
Beginners PHP
–157–
ID Title First_Name Surname
1 Mr Test Name
2 Mrs Second Test
The columns (ID, Title, First_Name, Surname) are called Fields. The rows are
called Records. Each record is a separate entry.
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, if you have version 1.8 of EasyPHP, type http://127.0.0.1/mysql/ to bring up
phpMyAdmin. However, if you have EasyPHP version 2.0, type
http://127.0.0.1/home/mysql/ instead.
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:
This is where you type a name for your database. We're going to create a simple
Address Book, so type that into the textbox:
After you have typed a name for your new database, click the "Create" button.
You will be taken to a new area:
Home and Learn
–158–
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, surname, address, etc. You can always add more
later, but just type 4 in there. In fact, type it out exactly as it is below:
When you've finished, click the Go button. Another, more complex, area will
appear:
Beginners PHP
–159–
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 now.
Setting up Fields in your database tables
We have four Fields in our table. Although they are set out in rows in the images
above, 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:
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?
To set the type of data going into a field, you select an item from the Type drop
down list. Click the down arrow to see the following list you can choose from:
Home and Learn
–160–
As you can see, there's quite a lot! But you won't use most them. For the values we
have in our four fields, we want to hold these Types:
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, 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
TINYINT Signed: -128 to 127. Unsigned: 0 to 255
SMALLINT Signed: -32768 to 32767. Unsigned: 0 to 65535
Beginners PHP
–161–
MEDIUMINT Signed: -8388608 to 8388607. Unsigned: 0 to 16777215
INT Signed: -2147483648 to 2147483647. Unsigned: 0 to
4294967295
BIGINT Signed: -9223372036854775808. Unsigned: 0 to
18446744073709551615
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.
Text Types
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:
TINYTEXT L+1 byte, where L < 2^8
TEXT L+2 bytes, where L < 2^16
MEDIUMTEXT L+3 bytes, where L < 2^24
LONGTEXT L+4 bytes, where L < 2^32
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:
TINYTEXT 256 bytes
TEXT 64 KiloBytes
MEDIUMTEXT 16 MegaBytes
LONGTEXT 4 GigaBytes
Home and Learn
–162–
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:
"TEXT "
"TENLETTERS"
VARCHAR
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.
For our fields, then, we'll use the following Types:
ID SMALLINT
First_Name VARCHAR
Surname VARCHAR
Address TINYTEXT
So select these from your Types drop down list:
Beginners PHP
–163–
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.
The other Field settings we'll take a look at are these:
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.
Extra
This is where you can set an auto increment value. This means adding one to the
previous record number. This is ideal for us, as we have an ID field. Then we don't
have to worry about this field. MySQL will take care of updating it for us
The three icons 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.
So, set a primary key for the ID field by selecting the radio button, and choose
Auto Increment from the Extra drop down list:
Home and Learn
–164–
Your field screen then, minus the parts we've ignored, should look like this:
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.
Click the Save button on the fields screen. 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
Adding records to a MySQL Table
To insert a new record to your table, select the Insert Link at the top of the page:
Beginners PHP
–165–
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.
To enter a new record in your table, you type your data in the textboxes under the
Value heading. Go ahead and enter the following information for the Value
textboxes:
ID: 1
First_Name Test
Surname Name
Address 12 Test Street
Home and Learn
–166–
Your screen should then look like this:
Finally, click the Go button at the bottom of the screen. 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:
Notice the folder name in the image above: addressbook. This is the same as the
database name, and is automatically created for you for all new databases. When
you double click this folder, you should see a few files there:
Beginners PHP
–167–
Notice the files names – they are the same as the tables you create. In other words,
they ARE the tables.
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.
Home and Learn
–168–
Manipulating a MySQL database with PHP
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
How to access a MySQL database with PHP code
PHP has a lot of inbuilt functions you can use to manipulate databases. In PHP
version 5, a lot more were added as well! Here, we'll stay with the inbuilt functions
for versions earlier than PHP 5. But if you have version 5, it's well worth
researching the newer database functions. A good place to start is php.net. To open
our database, we'll use the following inbuilt functions:
mysql_connect( )
mysql_select_db()
mysql_close()
The approached we'll take has three steps:
1. Open a connection to MySQL itself
2. Specify the database we want to open
3. Close the connection
Let's do Step 1 on the list.
Step 1 - Open a connection to MySQL
The first job is to actually connect to MySQL. As it's name suggests,
mysql_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.
<?PHP
$user_name = "root";
$password = "";
$database = "addressbook";
Beginners PHP
–169–
$server = "127.0.0.1";
mysql_connect($server, $user_name, $password);
print "Connection to the Server opened";
?>
Save your work and try it out on your server.
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";
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.
Hopefully, you won't have any errors. But the line that connects to MySQL is this:
mysql_connect($server, $user_name, $password);
So you type the name of the function first (mysql_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:
mysql_connect('127.0.0.1', 'root', '');
Or as variables, like we did at first:
$user_name = "root";
$password = "";
$server = "127.0.0.1";
mysql_connect($server, $user_name, $password);
And that's all you need to get you connected to MySQL. But we haven't connected
to the database yet. That's Step 2 on our list.
Home and Learn
–170–
Step 2 - Specify the database we want to open
In our code, we set up a variable with the name of our database:
$database = "addressbook";
We now need to do something with this variable. So add this new line to your code
(second from bottom):
$user_name = "root";
$password = "";
$database = "addressbook";
$server = "127.0.0.1";
mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database);
print "Connection to the Server opened";
You use the mysql_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.
You can use some logic to test if the database was found. Change the last two lines
of your code to this:
$db_found = mysql_select_db($database);
if ($db_found) {
print "Database Found";
}
else {
print "Database NOT Found";
}
Now change the database name from this:
$database = "addressbook";
to something like this:
$database = "addressbook2";
Beginners PHP
–171–
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.
But there's another option you can use for mysql_select_db – something called a
resource link identifier. It's just a file handle that you used in an earlier section
(opening text files). You use it like this:
$user_name = "root";
$password = "";
$database = "addressbook";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
print "Database Found " . $db_handle;
}
else {
print "Database NOT Found " . $db_handle;
}
So when we connect to the database, we're now using this:
$db_handle = mysql_connect($server, $user_name, $password);
It's just the same as before, except we're returning a value from the
mysql_connect function, and putting it into a variable called $db_handle. When
we connect to the database, we can use this file handle:
$db_found = mysql_select_db($database, $db_handle);
The resource link identifier (file handle) goes after the name of the database you
want to open. You can then use this file handle to refer to your database
connection.
Now that we've connected to MySQL, and connected to a database, it's time to
close the connection.
Step 3 - 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:
Home and Learn
–172–
mysql_close($db_handle);
Otherwise, you don't need to bother. It's recommended that you take the file handle
approach, though. That's what we'll be doing from now on.
So, we'll add a line to close our connection. Here what your code should now look
like:
<?PHP
$user_name = "root";
$password = "";
$database = "addressbook";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
print "Database Found ";
mysql_close($db_handle);
}
else {
print "Database NOT 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.
Reading records from a database
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, and print them out to the page. Here's some new code, added to the
PHP script you already have:
Beginners PHP
–173–
<?PHP
$user_name = "root";
$password = "";
$database = "addressbook";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM tb_address_book";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['ID'] . "<BR>";
print $db_field['First_Name'] . "<BR>";
print $db_field['Surname'] . "<BR>";
print $db_field['Address'] . "<BR>";
}
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_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 first line in the new code is this:
$SQL = "SELECT * FROM tb_address_book";
Home and Learn
–174–
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.
Structured Query Language
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:
SELECT * FROM Table_Name
SQL is not case sensitive, so the above line could be written:
Select * From Table_Name
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:
"SELECT all the records FROM the table called Table_Name"
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:
"SELECT First_Name, Surname FROM tb_address_book";
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.
Back to the code, then. The first line was this:
$SQL = "SELECT * FROM tb_address_book";
SO we have a SQL statement, but we need to pass it to another inbuilt function:
mysql_query( )
The mysql_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
Beginners PHP
–175–
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:
$result = mysql_query($SQL);
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:
$db_field = mysql_fetch_assoc($result)
The inbuilt function we're using to bring results back is this:
mysql_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
mysql_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]' =
And not this:
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 ( ) {
print $db_field['ID'] . "<BR>";
Home and Learn
–176–
print $db_field['First_Name'] . "<BR>";
print $db_field['Surname'] . "<BR>";
print $db_field['Address'] . "<BR>";
}
So we're printing whatever the value is in the array position $db_field['ID'],
$db_field['First_Name'], $db_field['Surname'] and $db_field['Address']. We're
also adding a HTML line break at the end, just for printing purposes.
If all that is confusing, just remember the format:
Array_Name[Table_Coulmn_Name] = Value_From_Record
Our whole while loop, then, is this:
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['ID'] . "<BR>";
print $db_field['First_Name'] . "<BR>";
print $db_field['Surname'] . "<BR>";
print $db_field['Address'] . "<BR>";
}
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 mysql_query( ) to bring back the records we've specified in Step 1
3. Use mysql_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
Step 1 was this, in the code:
$SQL = "SELECT * FROM tb_address_book";
Step 2 was this:
$result = mysql_query($SQL);
Step 3 was this:
$db_field = mysql_fetch_assoc($result)
Beginners PHP
–177–
And Step 4 was this:
while ( ) {
print $db_field['ID'] . "<BR>";
print $db_field['First_Name'] . "<BR>";
print $db_field['Surname'] . "<BR>";
print $db_field['Address'] . "<BR>";
}
If you're still confused, study the code and go over this section. In the next section,
we'll adapt the code to add more records to our database table.
Adding records to a database table
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:
1. Open a connection to MySQL
2. Specify the database we want to open
3. Set up a SQL Statement that can be used to add records to the database
table
4. Use mysql_query( ) again, but this time to add records to the table
5. Close the connection
We've already done steps 1 and 2 on the list. It's the same code as before. In fact,
you can use your script from the previous section.
So, open this script up, and save it under a different file name. Then delete the
following lines in italics below:
<?PHP
$user_name = "root";
$password = "";
$database = "addressbook";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
Home and Learn
–178–
if ($db_found) {
$SQL = "SELECT * FROM tb_address_book";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['ID'] . "<BR>";
print $db_field['First_Name'] . "<BR>";
print $db_field['Surname'] . "<BR>";
print $db_field['Address'] . "<BR>";
}
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
So you're deleting the SQL statement, and the While loop. Replace the SQL line
with this:
$SQL = "INSERT INTO tb_address_book (First_Name, Surname,
Address) VALUES ('bill', 'gates', 'Microsoft')";
The double and single quotes need to be entered exactly as they are above,
otherwise you'll get errors when we run the code. But your new code should look
like this:
<?PHP
$user_name = "root";
$password = "";
$database = "addressbook";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
Beginners PHP
–179–
$SQL = "INSERT INTO tb_address_book (First_Name,
Surname, Address) VALUES ('bill', 'gates', 'Microsoft')";
$result = mysql_query($SQL);
mysql_close($db_handle);
print "Records added to the database";
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
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.
INSERT INTO … VALUES
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 tb_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:
INSERT INTOtb_address_book (First_Name, Surname, Address)
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.
Home and Learn
–180–
To add values, you type the word "VALUES" after the round brackets of your
column names:
INSERT INTO tb_address_book (First_Name, Surname, Address) VALUES
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.
So our whole line reads:
$SQL = "INSERT INTOtb_address_book (First_Name, Surname,
Address) VALUES ('bill', 'gates', 'Microsoft')";
Notice how we've surrounded all of our text with double quotes. But inside of the
values round brackets, we've used single quotes.
The syntax is really this (The SQL keywords are in italics):
INSERT INTOtable_name ( Columns ) VALUES ( values for columns)
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 'bill', 'gates', and 'Microsoft' 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.
Using HTML Forms with your Database
You can use a HTML form to query your databases. But there are special security
considerations you need to bear in mind. We'll look at those issues in this section.
If you use things like text boxes and text areas on your forms, you need to take
care. This is because of an attacks like SQL injection. Things like single quotes
need to be escaped. But you can use an inbuilt PHP function for this:
mysql_real_escape_string()
We'll see how this works in a moment, but let's get some practical work done.
There is a file amongst the ones you downloaded called magicTest.php (in the
Beginners PHP
–181–
scripts folder). Load this script in your browser, with your server running. You
should see a text box and a button. Typed the following name into the text box:
O'Connor
Now click the button. You should see the name printed exactly as it is in the text
box.
So far, so good. Now, try this.
When you installed your server, there will be a file called php.ini. This is a list of
all the various settings to do with PHP itself. Locate this file called php.ini (in the
folder called apache, or do a search for it). Open it up in a text editor. Search for
this line:
magic_quotes_gpc = Off
Change the Off to On, if it's not already on. Then save the changes.
Now load up the your PHP script with the text box and the button. With O' Connor
still in the text box, click your button again. You should see this printed:
O \' Connor
So PHP has put a backslash before the single quote. But what's going on?
Magic Quotes
Characters like single and double quotes can be very dangerous, if you're running
SQL on your databases. These characters can be used to launch a SQL injection
attack on your database. So the makers of PHP came up with a function called
magic_quotes_gpc. If this is set to On, then PHP will add the backslash to all
single and double quotes. That way, an attacker's life is made more difficult. As an
example, we'll load up a database and a script. These are already prepared for you.
Amongst the files you downloaded there is a folder called databases. Inside this
folder there is a one called membertest. Save the entire membertest folder to
your data directory in your mysql folder. For EasyPHP users this will be at:
C:\PHP\EasyPHP1-8\mysql\data
Unless you have EasyPHP version 2.0, in which case the data directory is here:
Home and Learn
–182–
C:\Program Files\EasyPHP 2.0b1\mysql\data
Change the C to whatever letter your hard drive is.
Now set magic_quotes_gpc = On back to magic_quotes_gpc = Off in your
php.ini file.
Along with the database folder there is a PHP script called magicTest2.php (in the
scripts folder). We'll use this script, and the database, to teach you about SQL
injection. Not so that you can launch your own attacks, of course! It's so that you
can thwart them. Place magicTest2.php in your root folder.
SQL injection
When you open the magicTest2.php page in your browser, you'll see three
textboxes: one for a username, one for a password, and one for an email address.
There is also a button on the form.
Enter the following in the email address text box:
test1@test1.com
Click the button, and you should see following print out:
1
test1
test1
test1@test1.com
These correspond to the four fields in the database. The four fields are:
ID
username
password
email
So the username is test1, the password is test1, and the email address is
test1@test1.com.
Now, suppose you were naïve enough to have a database table exactly like that
one. An attacker will test to see if any syntax error messages can be returned. If so,
this means that the author of the script has not dealt with single/double quotes
correctly. The attacker can then go ahead with further probes.
Beginners PHP
–183–
Try your script again. Only this time, add a single quote to the end of the test email
address in the textbox:
test1@test1.com'
Now click the Submit button. What you should find is that an error message is
indeed returned. Something like this:
Warning: mysql_fetch_assoc(): supplied argument is not a valid
MySQL result resource
Because Magic Quotes are off, that single quote is not being escaped. The line in
our new script that is doing the damage is the one:
$SQL = "SELECT * FROM members WHERE email = '$email' ";
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 check. The value we
want to check is coming from the variable called $email. This is surrounded with
single quotes.
When an email address is entered in the text box on our form, this value goes
straight into the variable without any checks. When you type that extra single
quote on the end, that will be added to the SQL. This is then run on the database.
Because it's a stray single quote, you'll get a syntax error. It's this syntax error that
an attacker is looking for.
Next, the attacker will try to add some SQL to yours. Try this. In the email address
textbox, type the following. Type it exactly as it is, with the single quotes:
hi' OR 'x'='x
When you click the Submit button, you should find that there are no errors, and
that the username, password and email address are printed out!
The attacker is trying to find out whether or not the SQL can be manipulated. If
the answer is yes, further attacks will be launched. Can the table and field names
be guessed? Can a username and password be guessed? It's this kind of attack that
you want to thwart.
Try this last one. Enter the following into the email address box:
' OR ''='
Home and Learn
–184–
Now click Submit.
Again, the details are printed out. This is because an OR clause has been added.
The OR clause is set to a blank string. Meaning that the records will be brought
back if it's a valid email address or not!
To stop this kind of attack, you MUST use some inbuilt PHP functions. The one to
use for this kind of attack is:
mysql_real_escape_string( )
Between the round brackets, you type the string you need to check, followed by an
optional database handle. To test this out, there is another script like the one
you've just tried. This one is called magicTest3.php (in the same scripts folder). If
you open this up in your text editor, you should see this added to the code:
$email = mysql_real_escape_string($email, $db_handle);
Now, the $email variable is being checked for any of the following:
\x00
\n
\r
\
'
"
\x1a
If any of the above characters are found, a backslash is added. Try the new script.
Enter the following in the email address text box (with the single quote on the
end):
test1@test1.com'
What you should find is that the following gets returned:
test1@test1.com\'
So the single quote has had a backslash added to it. The point is that the dangerous
SQL doesn't get executed. Try the above attacks again. This time, you shouldn't be
able to get in, if any of the listed escape characters have been used.
But you need to use the function on all variables or data that will be used in your
SQL. So you should do this kind of thing:
Beginners PHP
–185–
$username = mysql_real_escape_string($username, $db_handle);
$password = mysql_real_escape_string($password, $db_handle);
$email = mysql_real_escape_string($email, $db_handle);
Examine the code in the new script. Pay attention to where the new lines go: after
you have opened a connection to your database.
The PHP manual recommends the following sample script, when working with
SQL (all comments are theirs; bold is ours):
<?php
// Quote variable to make safe
function quote_smart($value) {
// Stripslashes
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
// Quote if not integer
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password') OR
die(mysql_error());
// Make a safe query
$query = sprintf("SELECT * FROM users WHERE user=%s AND
password=%s", quote_smart($_POST['username']),
quote_smart($_POST['password']));
mysql_query($query);
?>
We have adapted the magicTest3 script, with the recommended code added, so
that you can see it in action. The new script is magicTest4.php. Open the script and
study the code. See if you can figure out how the new additions work.
But the PHP manual script above can be found at:
Home and Learn
–186–
http://us3.php.net/manual/en/function.mysql-real-escape-string.php
As well as using mysql_real_escape_string( ), you'll need to use the other function
you saw earlier, in the forms section - htmlspecialchars().
It can be a lot of work, dealing with SQL injection attacks, and handling all those
escape characters. But if you don't want your databases attacked, you HAVE to
defend yourself!
Limit the charcters that a user can enter
Another security technique that some advocate is to limit the characters that can be
entered. For example, you might have this in your script:
$valid_chars = "abcdefghijklmnopqrstuvwxyz";
$valid_nums = "1234567890";
$valid_other = "£$^&_@#~";
You can then use some Conditional Logic to test if the character the user entered
was on your list. If it's not, then you can display an error message.
An excellent walkthrough of security blunders can be found at:
http://www.sitepoint.com/article/php-security-blunders
Beginners PHP
–187–
Other things you can do with SQL
We'll go through some of the other things you can do with SQL, just so that you
can get an idea of how they work. But you'll meet more SQL when we start our
walkthroughs. All of the walkthroughs use databases and SQL. An excellent
introduction to SQL can be found here:
http://www.tizag.com/sqlTutorial/index.php
Create a Table using SQL
You can create tables using SQL (and whole databases), and specify the fields you
want to go in the table. However, doing it this way is not recommended: you tend
to forget which fields are in the table, their data types, which field is the primary
keys, and which ones are set to NULL values. If you can get to grips with visual
tools like phpMyAdmin then so much the better.
To create a table then, you use the CREATE keyword (known as a clause, in
database speak). Here's the SQL to create the simple address book we've been
using. This assumes that the database itself already exists, and that the PHP code
to open a connection has already been written (you saw how to do this in a
previous section):
$SQL="CREATE TABLE AddressBook
(
ID int(7) NOT NULL auto_increment,
First_Name varchar(50) NOT NULL,
Surname varchar(50) NOT NULL,
email varchar(50),
PRIMARY KEY (ID),
UNIQUE id (ID)
)";
mysql_query($SQL);
So you start with the Clause CREATE TABLE. Then you type the name of the
table you want to create. In between round brackets, you type the name of your
table Columns, followed by some formatting. In the code above, the first field
being set up is this:
ID int(7) NOT NULL auto_increment,
Home and Learn
–188–
The column name will be ID. The data type is an integer that is no longer that 7
digits. NOT NULL means you want something in this field, and that it can't be left
blank. The ID number will be auto incremented, whenever a new record is added.
Notice that there is only one comma in the line. The comma separates each field
you want to create in your table.
We're also setting up three other columns here: First_Name, Surname, and email.
First_Name and Surname can't be left blank ( NOT NULL), but email can be.
At the end, we have these two lines:
PRIMARY KEY (ID),
UNIQUE id (ID)
The primary key is used for things like joining data from one table to the data from
another. We've set this to our ID field. Primary keys don't have duplicate values,
so we've set this to be a UNIQUE field.
Once you've written your SQL statement, you can go ahead and execute it:
mysql_query($SQL);
Creating tables like this means a lot of extra, tricky work for you as a PHP
programmer. If you can use a tool to do the job for you, then your coding life gets
easier!
Updating a record in a table
You can also update a record in your table. Not surprisingly, the word UPDATE is
used for this. Here's an example:
$SQL = "UPDATE AddressBook SET email = 'new_email_address'
WHERE First_Name = 'Bill' AND Surname = 'Gates'";
After the word UPDATE, you need the name of the table you want to update.
Then you need another Keyword: SET. After the word SET, you type the name of
the Column you want to change. In the SQL above, we're changing the email
column. But notice the WHERE clause. We've specified that the record to change
should have the First_Name of Bill and the Surname of Gates.
You can also update an entire column, and change all the values:
UPDATE AddressBook SET Surname = LOWER(Surname);
Beginners PHP
–189–
Again, we've specified that the AddressBook table should be updated. We've SET
the column name as Surname. After an equals sign, we've used the inbuild SQL
function LOWER( ). This changes a value to lower case letters. In between the
round brackets of the function, we've typed the column name again. This will
ensure that all the text in the Surname column gets changed to lower case.
Deleting a record in a table
If you want to delete a record in a table, use the DELETE Keyword. Like this:
$SQL = "DELETE FROMAddressBook WHERE First_Name = 'Bill'
AND Surname = 'Gates'";
After the DELETE word, you need FROM. Then you type the name of the table.
Next, you need to specify which record you want to delete. It's a good idea to
make sure your WHERE clause is going to be a unique value. In the code above,
we might have more than one Bill Gates in the table. If we do, everybody called
Bill Gates will be deleted! A better solution is to use a unique field from your
table, such as an ID field:
$SQL = "DELETE FROMAddressBook WHERE ID = '7' ";
Now, only the record that has number 7 in the ID field will be deleted.
Using WHERE to limit the data returned
You can add a WHERE part to your SQL. But before you do, make sure you read
the security section.
Using WHERE limits the records returned from a SQL statement. Most of the
time, you don't want to return all the records from your table. Especially if you
have a large number of records. This will just slow things down unnecessarily.
Instead, use WHERE. In the SQL below, we're using WHERE to bring back only
the matching records from the AddressBook table.
$SQL = "SELECT * FROM AddressBook WHERE email = 'me@me.com' ";
When the following code is run, only the records that have an email field of
me@me.com will be returned.
You can specify more fields in your WHERE clause:
Home and Learn
–190–
$SQL = "SELECT * FROM AddressBook WHERE First_Name =
'Bill' AND Surname = 'Gates'";
In the SQL statement above, we've used the AND operator as well. Only records
that have First_Name value of Bill AND a Surname value of Gates will be
returned.
You can also use the operators you saw in the variables section:
$SQL = "SELECT * FROM AddressBook WHERE ID >= '10' ";
In this SQL statement, we're specifying that all the records from the AddressBook
table should be returned WHERE the ID column is greater than or equal to 10.
Getting the hang of WHERE can really speed up your database access, and is well
worth the effort. An awareness of the security issues involved is also a must.
In the next sections, we'll take you through some fuller projects, and explain the
code, and the things you need to consider when working on bigger projects like
this. First up is a username and password system.
Beginners PHP
–191–
User Authentication Walkthrough
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 at the start of the
book. (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. Other things you need to consider before
implementing a login section on your site are discussed at the end of this section.
You need to read these!
A word about the database used for this section
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. The database can be found in the
databases folder. Copy this to the data directory of you mysql folder, just like you
did before.
The database table has a test username and password set, so that you can try it out.
The username is usernameTest and the password is passwordTest. Also, make
sure cookies are enabled in your browser. You'll see why, later.
But let's get started.
The login page
The first script to take a look at in the login folder is login.php. Open up this script
in a text editor, and well see how it works. Of course, 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 submit button. It will look like this:
Home and Learn
–192–
The HTML for this form can be seen at the bottom of the login.php script that you
have (hopefully) by now opened. There's nothing special about it. But notice that
there's a PHP print statement in the HTML Body section:
<?PHP print $errorMessage;?>
This is for displaying error messages for the user.
The first few line of the script, though, just set up some variables:
$uname = "";
$pword = "";
$errorMessage = "";
$num_rows = 0;
The $errorMessage variable is an important one. We'll add something to this
variable, if an error occurs. We'll then check to see if it's blank or not.
The next part of the code is just the SQL checking function you met earlier. This
aims to prevent SQL injection attacks. After this code, we check to see if the form
has been POSTED or not (was the Submit button clicked):
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
}
Most of our code goes between the curly brackets of this if statement. The first
thing to do is to get the username and password from the textboxes:
Beginners PHP
–193–
$uname = $_POST['username'];
$pword = $_POST['password'];
We then deal with any unwanted HTML (scripting attacks):
$uname = htmlspecialchars($uname);
$pword = htmlspecialchars($pword);
Next, we attempt to connect to the database:
$user_name = "root";
$pass_word = "";
$database = "login";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
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 {
$errorMessage = "Error logging on";
}
If the database isn't found, then some text is added to the error message variable. If
the database was found, strip the incoming text of any unwanted characters (SQL
Injection attacks). These next two lines call the function at the top of the code:
$uname = quote_smart($uname, $db_handle);
$pword = quote_smart($pword, $db_handle);
With the username and password sanitised, we can then set up a SQL command.
We're selecting all the records in the database where the incoming username and
password match the database table fields called L1 and L2:
$SQL = "SELECT * FROM login WHERE L1 = $uname AND L2 = $pword";
Next, issue the SQL command using mysql_query( ):
$result = mysql_query($SQL);
We need to check what is returned by the mysql_query() function. The value in
$result will either be true (if any records are returned) or false (if none are
Home and Learn
–194–
returned). We're checking to see if there were any errors when the SQL command
was issued against the database table. If so, put something in the error message
variable:
if ($result) {
}
else {
$errorMessage = "Error logging on";
}
If the SQL command was issued successfully, you can see how many rows were
returned from the database table. The inbuilt function mysql_num_rows( ) is used
for this. If no rows were returned, then that tells you that there's something wrong
with either the username or password.
$num_rows = mysql_num_rows($result);
Next, we test the $num_rows variable to see if it's greater than zero. If it is, then
you have a successful logon. If not, then it's invalid.
if ($num_rows > 0) {
$errorMessage= "logged on ";
}
else {
$errorMessage= "Invalid Logon";
}
In the above code, the number of rows returned could be greater than 1. That
would mean that 2 or more people have the same username and password. If you
have a website where each user has to be unique, then you obviously want to
check if $num_rows = 1. For some websites, it doesn't really matter if 2 or more
people have the same login details. But for things like forums, where people are
posting and replying to the input of others, then it does matter. After all, you want
to credit forum users with the correct posts. For the purpose of this tutorial, assume
that it doesn't matter if login details are the same.
Setting a Session
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
Beginners PHP
–195–
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.
In the previous code, the part that checked if the user was OK was this:
if ($num_rows > 0) {
$errorMessage= "logged on ";
}
else {
$errorMessage= "Invalid Logon";
}
The code checks to see if the number of rows returned from a SQL command is
greater than zero. If it is, then the user is OK. But the code in the login.php script
is slightly different. It's this:
if ($num_rows > 0) {
session_start();
$_SESSION['login'] = "1";
header ("Location: page1.php");
}
What the code does is to set up a session variable. The value in the variable will be
1, if the user logs on successfully. To set up a session variable, you need to issue
the 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[ ]
In between the square brackets of $_SESSION, you type the name of your
variable. Like all variable names, you can call it almost anything you like. Storing
values in the session variable is just the same as storing values in a normal
variable:
$_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.
header ("Location: page1.php");
Home and Learn
–196–
For the else part of the if statement, the code is this:
if ($num_rows > 0) {
session_start();
$_SESSION['login'] = "1";
header ("Location: page1.php");
}
else {
$errorMessage = "Invalid Login";
session_start();
$_SESSION['login'] = '';
}
Here, we add something to the error message variable:
$errorMessage = "Invalid Login";
Next, we issue the "start session" command:
session_start();
But the next line puts something different in to the session variable:
$_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
refuses 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. A good run down on cookies, and
how to use them, can be found here:
http://www.devpapers.com/article/335
Beginners PHP
–197–
You'll also see a script that you can adapt to check if cookies have been enabled on
the browser.
And that's about it for the login script. Here's a run down on what we did:
€”Got the username and password from textboxes on a form
ۥOpened a connection to a database
€–Validated the username and password
€—Checked to see if any rows were returned from the database
€˜If rows were returned, set a session variable to 1
€™If no rows were returned, set a session variable to a blank string
€šBuilt up an error message throughout the code
But the point about setting a session variable is so that you can then check its value
when users go to other pages on your site. We'll see how to do that now.
Checking if the user is logged on or not
On all pages of your site that you want to secure, you'll need to check if the user
was successfully logged on or not. After all, what's to stop non members from
simply typing the address of the page in their browsers? If you haven't set any
checks, then the page will load, whether they are a member or not. To stop this
happening, you can check the session variable that you set up on the login page.
If you open up the page called page1.php, you'll see this code at the top:
<?PHP
session_start();
if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
header ("Location: login.php");
}
?>
This checks to see if the session called login is set, and that it's not a blank string.
If it is, then the user is redirected to the login page. In the script, you first start the
session:
session_start();
Next comes a complex If statement:
Home and Learn
–198–
if ( ) {
header ("Location: login.php");
}
In between the round brackets of the If statement, we have the NOT operator. This
is followed by the inbuilt isset() function:
if ( !(isset( ) ) {
}
This says, "If NOT isset". Or, "if the value of the isset function is false ... " If the
value in the round brackets of isset is indeed false, then the code between the curly
brackets { } gets executed. That code, for us, was the redirection line. What we
have between the round brackets of isset is this:
($_SESSION['login'])
That's just our session variable from the login page. Is the user has logged in
successfully, a value of 1 will be set inside of this variable.
But we also need to check the session variable for a blank string. So we have and
AND part to the statement:
&& $_SESSION['login'] != ''
This says, "AND session login DOES NOT EQUAL a blank string". In other
words, we check to see if a session variable has been set, and that it's not a blank
string.
If everything is OK then the user will see the HTML code below the PHP at the
top. If it's not, you can send them somewhere else. But you need to put that PHP
code at the top of every page that you want to protect. And it needs to go before
any HTML code. You can't put it in the head section, otherwise you'll get "header"
errors.
Log Out
You'll also want to ensure that your users can log out successfully. This is quite
easy, as the only thing you need to do is to destroy the session. Fortunately, PHP
has an inbuilt function for that:
session_destroy();
Beginners PHP
–199–
When this function is executed, all the session variables that you set up for the user
will be destroyed. Open up the page called page2.php, and take a look at the code.
It's just this, though:
<?PHP
session_start();
session_destroy();
?>
Quite bizarrely, you have to start the session first, even though you've been using
sessions throughout your pages! So that the user can log out, you can add a link on
your page1.php page:
<A HREF = page2.php>Log out</A>
When the user clicks this link, the log out script will be executed. If you try to
reload page1.php, you'll be redirected to the login page.
Register a new user
If the user is new to the site, and wants to sign up, you can add a link to a "sign
up" page. Open up the signup.php page, and you'll see some code already there.
We'll now walk you through what it all does.
When you open up the code for the signup.php page, you'll see quite a lot of it is
code that you've already met. It starts with the function that checks for dangerous
SQL characters. Then we check that the form has been POSTED. The next lines
are these:
$uname = $_POST['username'];
$pword = $_POST['password'];
$uname = htmlspecialchars($uname);
$pword = htmlspecialchars($pword);
We're just getting the username and password from the form, like we did before,
and then checking it for unwanted tags. The next thing you need to do, though, is
test that the username and password are of the correct length. You don't want a
malicious user trying to inject megabytes of text!
$uLength = strlen($uname);
$pLength = strlen($pword);
Home and Learn
–200–
if ($uLength >= 10 && $uLength <= 20) {
$errorMessage = "";
}
else {
$errorMessage = $errorMessage . "Username must be between
10 and 20 characters" . "<BR>";
}
if ($pLength >= 8 && $pLength <= 16) {
$errorMessage = "";
}
else {
$errorMessage = $errorMessage . "Password must be between
8 and 16 characters" . "<BR>";
}
What we're doing here is using the inbuilt function strlen( ) to get the length of the
string. We then use if .. else statements to check that the username and password
are between certain values. If they are ok, the variable called $errorMessage is
left blank. If they are not ok, we add some text for the error message.
Before checking the username and password against the database, we can check to
see if the error message is blank:
if ($errorMessage == "") {
}
If it's blank, then everything is ok. In which case the rest of the code is executed. If
it's not OK, then the user will see the text of the error message displayed.
Inside of the if statement for the error message check, we just set up the database
code like we did before:
$user_name = "root";
$pass_word = "";
$database = "login";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
}
Beginners PHP
–201–
We're just checking that the database can be found. If it is, then we need to check
if the username has already been taken:
$SQL = "SELECT * FROM login WHERE L1 = $uname";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "Username already taken";
}
else {
}
The code attempts to select all the records from the table where a match with the
username is found. (L1 is the name of the username field in the table.) If any
records are returned, then the variable called $num_rows will be greater than zero.
We check the value of $num_rows in an if ... else statement.
If the username has already been taken, then we can add something to the error
message variable. (But there are security considerations to bear in mind here. Do
you really want to tell a malicious user that a username has already been taken? If
it's for a forum, then it's ok: the malicious user can simply read usernames from
forum posts. But in that case, perhaps we shouldn't be using a username to log
people in?)
If the value in the variable $num_rows is still zero, then we can go ahead and add
the user to the database:
$SQL = "INSERT INTO login (L1, L2) VALUES ($uname, $pword)";
$result = mysql_query($SQL);
mysql_close($db_handle);
Here, we use the SQL command INSERT INTOto add a new record to the
database.
After the user has been added to the database, we can then set the session variable:
session_start();
$_SESSION['login'] = "1";
The session variable called login will be set to 1. This means that the user can then
start using the site straight away. In fact, we redirect them to a different page on
the site:
Home and Learn
–202–
header ("Location: page1.php");
Our new user is now a member!
Other considerations
The above sign up script is fairly simple, and there other things to consider. Here's
a few of them.
Validation
Some sites ask you to provide an email address when signing up. (An alarming
number of them!) They then send you your login details and confirmation via
email, with perhaps a hyperlink that you need to click on to verify the details. You
would then enter the verification code or codes before you can start using the site.
To do this, you would need to add more fields to your database table - an email
address field and a verified field. The verified field would be set to NO, by default.
You could then check this field from all pages of your site. If it still says NO, then
the user hasn't yet confirmed the login details. In which case, don't let them in. The
verified field would only get set to YES if the user went to the page mentioned in
the email and entered the correct details.
This type of script is more complex to set up, and tends to be more frustrating for
the user. And there is always a sneaking suspicion that your email address is being
sold off to the nearest spammer!
Passwords
If you need to save a password to your database table, then you have to encrypt the
details. If you look at the signup script, you'll notice the use of this function:
md5(pword)
The inbuilt function md5() returns a 32-character hexadecimal number, based on
the string you type between its round brackets. You then save this "hash" number
to your password field. Or do it all in one go, with your SQL statement:
$SQL = "INSERT INTO login (L1, L2) VALUES ($uname, md5($pword))";
The L1 field is for the username and the L2 field for the password. The VALUE
for the password now goes between the round brackets of md5()
Beginners PHP
–203–
When you check the password field on the login page, you'd then do this:
$SQL = "SELECT * FROM login WHERE L1 = $uname AND L2 =
md5($pword)";
Again, the password goes between the round brackets of md5(). But storing
passwords in encrypted format is highly recommended!
Some more things worth considering on your login/signup pages:
€›Test if the users is already logged in. That way, they can't sign up
repeatedly without closing down the browser
€œSet a cookie for logins, instead of using sessions. You then need to write
code to read the cookie data back for every protected page on your site.
ۥCollect other information, and store then in your database tables: date and
time of login, IP address, etc
€žUser's forget their usernames and password. You'll need a link to send
them the details. However, don't forget to add some extra security here!
Something like a password reminder (memorable date, favourite teacher,
etc) is recommended.
€ŸEnumeration attacks are quite a common way for malicious users to try and
gain access to your site. This is when the attacker can simply sit at his/her
pc screen and enter the username and password over and over again,
looking for "error message" clues. To thwart this type of attack, you might
want to limit how long a user has to log on to your site. A good way to do
this is by setting a session to end after so many minutes. This page is worth
exploring, for such script ideas: http://www.weberdev.com/get_example-
4267.html
Conclusion
Although our login/sign up 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!
Home and Learn
–204–
Build your own Survey Application
The Survey web application consists of 5 PHP files and a database. You'll see
what they all do as we go along. But there are separate sections: A section where
you can set a question for your visitors; a section that allows visitors to vote on
your question; and a section where the results can be viewed. The survey itself
looks like this, on the page:
When you click the Vote button, your choice will be recorded in the database. If
you click the "View Results" button, you'll see this:
You'll learn how to code for all of this. But we're going to start with setting a
question for the survey. Off we go.
Set a Question for your Survey
To set a question for your survey, you simply type the question into textboxes on a
form. You then set the options that a visitor can choose from. The Form to set a
question looks like this:
Beginners PHP
–205–
To test this out, locate the folder called survey, which is amongst the files and
folders you downloaded at the start of the book (in the scripts folder). Copy the
entire survey folder over to your www folder. Now load up the setQuestion.php
page in your browser by typing:
127.0.0.1/survey/setQuestion.php
You should see the web page as above that allows you to set a question. This is
just a simple HTML form that has no special formatting applied, and so looks a bit
messy! But you can use this to add questions to your Survey database.
But don't click the button on the form yet, or you'll get an error message. First,
copy the database folder called surveytest to your mysql/data folder. You data
folder should then look like this:
Home and Learn
–206–
To see if the database has been copied ok, type this into the address bar of your
browser (this assumes that your server is up and running):
http://127.0.0.1/mysql/
If you have EasyPHP version 2.0, however, you need to type this instead:
http://127.0.0.1/home/mysql/
What you're trying to do is to bring up the phpMyAdmin page. This one:
We'll now take a look at how the database is set up, because it's the key to
understanding how the survey web application works.
The database
From the left hand side of the phpMyAdmin screen, under "Please select a
database", have a look at the items on the drop down list. You should see one
called surveytest.
Beginners PHP
–207–
If you can't see surveytest there, it means you haven't copied the surveytest folder
to the correct place.
If you can see surveytest, select it from the drop down list. You should see the
names of two tables appear:
Click on tblQuestions, and you'll see the Structure for this Table:
Home and Learn
–208–
Under the Table heading, you'll see the two tables in this database: answers and
tblQuestions. Click on the Browse icon for tblQuestions, as in the image below:
You will be taken to the Field names and Rows in the table:
The Field names run from left to right, and are important. They are:
QID
Question
qA
qB
qC
Beginners PHP
–209–
The tblQuestions table above has four rows of data, one for each question. The
QID field is the one to pay attention to. The values in the sample table are q1, q2,
q3, and q4. This QID field is the Primary Key in this table. This means that the
data in this field has to be unique. You can then use this QID field to identify each
row in the table. This same field, QID, is also in the answers table, along with the
qA, qB, qC fields. This allows you to select all the records in both tables based on
the QID field. You just pull all the records that match. For example, you can say
"Select all the records in both tables where the QID field equals q1".
Take a look at the answers table by clicking the link on the left hand side. Then
click on Browse at the top. You should see this:
In the answers table, the unique field (the primary key) is the ID field. This is just
an auto incrementing number that you used in an earlier section. You don't have to
worry about this field. But notice that the QID field is also there, along with the
same values from the tblQuestions table: A, B, and C. This matching field in the
answers table is something called a foreign key, in database terminology. Joining
data from a primary key in one table to a foreign key in another is common
technique in database creation. You do this when you want to keep data separate,
and to avoid having too many fields in a single table. It also speeds things up. In
our example database, we can keep the questions and answers separate.
(NOTE: If you have some knowledge about databases, you'll know about
Referential Integrity. Unfortunately, phpMyAdmin doesn't enforce this. So if you
delete a row from one table, the corresponding row in another table won't get
deleted - you have to code for that yourself!)
The A, B, and C fields in the answers table record how many people voted for
each option of your question. So, for question four (q4) 28 people voted for option
A, 127 people voted for option B, and 52 people voted for option C. If you look at
the matching row (q4) in the tblQuestions table you'll see that the question was:
Do you believe in UFOs? (These answers were entered by us - it's not real data!)
Now that you have a good idea about how the database works, let's go through the
code that sets a question.
Home and Learn
–210–
Setting a question – the code
Using your favourite text editor, open up the file called setQuestion.php again,
and take a look at the code. Most of it is code you've already met. In the first two
sections we just get the data entered in the textboxes on the form (the questions
and three possible options), check for any unwanted script tags, and then open up a
connection to the database. The first new code is this:
//============================================
// GET THE LAST QUESTION NUMBER
//============================================
$SQL = "Select * FROMtblQuestions";
$result = mysql_query($SQL);
$numRows = mysql_num_rows($result);
$boolLastRow = mysql_data_seek($result, ($numRows - 1));
$row = mysql_fetch_row($result);
$qID = $row[0];
$next_Q_Number = ltrim($qID, 'q');
$next_Q_Number++;
$question_Number = 'q' . $next_Q_Number;
As the comments say, we're getting the last question number from the tblQuestions
table. We need to do this because the primary key doesn't auto increment.
Because the primary key is a unique field, the auto increment feature of MySQL
would have added one to the primary key for us. But we've made our own unique
field to be used as a primary key, so we're going to have to increment the values
with code. The idea is that we get the last number value from the QID field, then
add 1 to it. (For simplicity's sake, there's no checking to see if the value we write
back to the database is indeed unique. If it isn't, you'll get an error. You'll see how
to code for this in the next section.)
The code, then, start off by getting all the records from the tblQuestions table:
$SQL = "Select * FROM tblQuestions";
Next, we try to run this query:
$result = mysql_query($SQL);
Beginners PHP
–211–
We could check here if the value in the variable called $result is true. If it wasn't,
we could display an error. (Another thing for you to do!) But we're keeping things
simple, so you can see how all this works.
The next thing to do is to get the number of rows in the table:
$numRows = mysql_num_rows($result);
We need to get the number of rows so that we can move the pointer to the last row
in the database. We want to get this last row so that we can check the QID field.
Remember: we're trying to add 1 to the value in the QID field - to increment it.
The code that moves the internal pointer to the last row in the database is this:
$boolLastRow = mysql_data_seek($result, ($numRows - 1));
We're using an inbuilt PHP function called mysql_data_seek( ). This allows you
to jump to any row in a table. Between the round brackets of the function, you first
type the name of your resource ($result, for us). Then, after a comma, you put the
row that you want to jump to: $numRows - 1. The count with mysql_data_seek( )
starts at zero, so we're deducting one from the number of rows in our table.
Otherwise, we'd get an error about no such row found. We're returning all this to a
boolean variable called $boolLastRow. You can write an error message, if this
returns a value of false. But we're leaving out the error checking here.
Once we've moved the pointer to the last row in the table, we can fetch the data
back:
$row = mysql_fetch_row($result);
You've met the inbuilt function mysql_fetch_row( ) before. It fetches a row of
data, and puts it all in to an array. You can then access the array, and manipulate
the data.
$qID = $row[0];
The QID field is at position zero in the array (it's the first field in the database). So
we just use $row[0] to return the value. This is then put in to the variable we've
called $qID. This variable will then hold the last QID value from the table. The
format we're using for the QID field is to type a letter "q" followed by a number.
To increment the QID field, we can just add 1 to the number then join that number
to the letter "q". The next few lines do exactly that:
$next_Q_Number = ltrim($qID, 'q');
$next_Q_Number++;
$question_Number = 'q' . $next_Q_Number;
Home and Learn
–212–
We use the ltrim function to strip off the letter "q". This leaves just the number
itself. You can then increment this number (next_Q_Number++). The final line
joins the new data back together:
$question_Number = 'q' . $next_Q_Number;
This adds the new number to the letter "q", and then stores it in a variable called
$question_Number. It's this question number that will get written to the QID fields
in both the tblQuestions table and the answers table.
The next two sections use the INSERT INTO command to add the new question to
the database. The first thing to do is to add the question to the tblQuestions table.
The rather long SQL line that does that is this:
$SQL = "INSERT INTO tblquestions (QID, Question, qA, qB,
qC) VALUES ('$question_Number', '$question', '$answerA',
'$answerB', '$answerC')";
You've met code like this in a previous section. You should be able to figure out
what it does: adds the data into the Field names mentioned in the first round
brackets.
To update the table, we run the SQL query:
$result = mysql_query($SQL);
The next SQL command is slightly different:
$SQL = "INSERT INTO answers (QID, A, B, C) VALUES
('$question_Number', 0, 0, 0)";
Again, it's an INSERT INTO command, but note that we're now updating the
answers table. The VALUES between the round brackets are:
'$question_Number', 0, 0, 0
The value inside of $question_Number will be the QID number. But the next three
values are all zero. This sets up the answers table, and ensures that the default
options are all filled in. A, B and C, remember, will hold the number of votes. We
start them off at zero because nobody has voted yet!
And that's about it for setting the question. We've covered quite a lot of ground in
a short space of time, so let's review what we did.
€ Created two tables in the same database
€Had a primary key in one table that is joined to a foreign key in the other
table
Beginners PHP
–213–
€Wrote code to move an internal pointer to the last record in a table
€Returned a specified row, and incremented a value to be used as a unique
key
€Inserted a new record into two tables, using the same field in both
Probably the most important thing to learn in this section is how to join separate
tables together using a primary/foreign key combination. We'll use this technique
again when we create a forum. For now, let's move on to the survey itself.
Adding a Survey to your page
The survey itslef can be found in the survey folder and is called survey.php. Open
up the this page in a browser by typing the following address:
127.0.0.1/survey/survey.php
You should see this:
All we have here is a question, and three possible answers. To vote, you select an
answer and click the button. When you do, you're taken to another page which
thanks you for voting. On the page, there is also a button that allows you to view
the results. Let's see how it all works.
To see the code for the survey, open up survey.php in your text editor. The first
line you'll see is this:
include 'sqlSurvey.php';
Home and Learn
–214–
The include file is an important one. Open up this file (also in the survey folder),
and you'll see that it's just a SQL command. This SQL is used to pull a question
from the database.
The code is this:
$qNum = 'q4';
$SQL = "SELECT * FROM tblquestions WHERE
tblquestions.QID = '$qNum'";
Only two lines long! The first line sets the question number. This is the QID field
from the tblQuestions table. To set a new question, the only thing you have to
change is this value. Try it. Change 'q4' to one of the other three values in the
table: q3, q2, or q1. Save the file, and reload survey.php in your browser. You
should see the question and answers change.
The important part of the SQL line is this:
WHERE tblquestions.QID = '$qNum'
We're saying select all the records WHERE the QID field matches the value in the
variable called $qNum. That's enough to pull the question and answers from the
table! But although the file is included on the first line, the code inside of it doesn't
get run till a little later.
The next few lines just set up some variables, and put default values in them. After
that, we add the code that opens up the database. You've met all this before, so we
won't go into it.
The part of the code that uses the include file is this:
$result = mysql_query($SQL);
The variable called $SQL is in the include file. The survey code can see this
variable because of the include directive. So it knows what's inside of it.
If mysql_query( ) succeeds, we can put the values into an array with the next line
(though you should write could for false values inside of $result):
$db_field = mysql_fetch_assoc($result);
The data from the SQL is then placed into an array called $db_field. You can get
at these values like this:
Beginners PHP
–215–
$qID = $db_field['QID'];
$question = $db_field['Question'];
$A = $db_field['qA'];
$B = $db_field['qB'];
$C = $db_field['qC'];
Here, we're returning the values from the following fields in the table: QID,
Question, qA, qB, and qC. We've put these into variables of their own.
Once we have the question and the answers, we can put these into the HTML on
the page. There are two HTML forms on the page. The first is this:
<FORM NAME ="form1" METHOD ="GET" ACTION ="process.php">
<?PHP print $question; ?>
<P>
<INPUT TYPE = 'Radio' Name ='q' value= 'A' <?PHP print
$answerA; ?>><?PHP print $A; ?>
<P>
<INPUT TYPE = 'Radio' Name ='q' value= 'B' <?PHP print
$answerB; ?>><?PHP print $B; ?>
<P>
<INPUT TYPE = 'Radio' Name ='q' value= 'C' <?PHP print
$answerC; ?>><?PHP print $C; ?>
<P>
<INPUT TYPE = "Submit" Name = "Submit1" VALUE =
"Click here to vote">
</FORM>
The question from our code is placed on the page with this line:
<?PHP print $question; ?>
This is the value that we got from the field in the tblQuestions table.
The code for the answers is then added to the radio button on the form:
value= 'A' <?PHP print $answerA; ?>><?PHP print $A; ?>
The "print $answerA" part will just add a value of checked or unchecked to the
radio button, depending on whether it was selected or not. An answer is added to
the radio button like this:
Home and Learn
–216–
<?PHP print $A; ?>
Whatever data we pulled from the A "field" in the table will end up in the variable
called $A. This is then printed to the page.
If the button is clicked, though, we're sending it to a page called process.php. We'll
take a look at that in a moment, but notice the second Form on the page:
<FORM NAME ="form2" METHOD ="GET" ACTION ="viewResults.php">
<INPUT TYPE = "Submit" Name = "Submit2" VALUE =
"View results">
<INPUT TYPE = "Hidden" Name = "h1" VALUE = <?PHP
print $qID; ?>>
</FORM>
This is for the "View Results" page. When this button is clicked, it goes to a new
page: viewResults.php. But there is a crucial HTML form element in the form
code:
<INPUT TYPE = "Hidden" Name = "h1" VALUE = <?PHP print $qID; ?>>
This sends the QID number to the viewResults page. We can then use this value to
pull the correct records from the two tables. You'll see how this works soon. But
one more thing to notice: both forms use the GET method to hand data to the next
page. Now let's move on to the code for the process.php page.
Add the Vote to the database
When the Vote button is clicked, the user will be sent to a new page. Behind the
scenes, you're recording the vote and adding it the database.
As well as adding the vote to the database, you'll probably want to implement
some sort of check to prevent people from voting over and over again. If you open
up the code for the process.php page (in the survey folder), you'll see that the
checking is done via a session variable. You met this code during the
username/password walkthrough.
session_start();
if ((isset($_SESSION['hasVoted']))) {
//Already Voted
}
else {
Beginners PHP
–217–
//Process the Vote
}
(NOTE: Session variables work by sending you an ID as a cookie. If you have
cookies disabled then the session variable won't work, and you can vote over and
over again! You might want to check that cookies are enabled in the browser.)
So we start a session, and check if the session variable called hasVoted has been
set. If it has, then a vote from this user has already been added to the database. In
which case, a message is displayed.
If no session has been set, then the else part of the if statement is executed. The
first line of this is another if statement:
if (isset($_GET['Submit1']) && isset($_GET['q'])) {
}
Here's we're checking for two things: was the Submit button called Submit1
clicked on the previous page, and has the radio button data been handed over to
this page (the radio button data will be in the variable called 'q')? If the answer to
both questions is Yes then we can go ahead and process the data; if the answer is
No, then we can assume that the button was clicked but the user didn't select a
radio button. In which case, this message is displayed: print "You didn't selected a
voting option!";
If all went OK, though, the first line of the new if statement to get executed is this:
$selected_radio = $_GET['q'];
This just gets which radio button was clicked. The value comes from the HTML
form, and will be A, B or C. This is then placed into the variable called
$selected_radio.
The next few lines open a connection to the database, like we did before. After the
database has been successfully opened, we have this:
$_SESSION['hasVoted'] = '1';
This is our "hasVoted" session variable, and we're placing a value of "1" into it. If
the user tries to vote again, a message of "You've already voted" will be displayed.
The next line is where we add the record to the answers table in our database:
$SQL = "UPDATE answers SET $selected_radio = $selected_radio + 1";
Home and Learn
–218–
Here, we're using the SQL command UPDATE. After the word UPDATE, you
type the name of the table you want to UPDATE (answers, for us). We only want
to update the field that was passed to the page in the "q" variable. This will be
either A, B or C, which are the column names from the answers table. We can then
use the SET keyword to set just that column from the table. Because the variable
called $selected_radio will contain only A, B or C we can just add 1 to whatever is
currently there:
SET $selected_radio = $selected_radio + 1";
You'll notice that we're not making sure to move to the end of the records in the
answers table (which we should do), but trusting MySQL to do it for us.
This is not a good idea! In your own code, you should make sure that the correct
record is being updated. We're taking shortcuts for simplicity's sake.
After the table is updated, we close the connection to the database, and print out a
message: "Thanks for voting".
And that's it - a vote has been added to the table.
You can add a "back" link to the HTML, or do anything else you like with your
page. Or perhaps you could add a link so that the results of the voting can be
viewed? We'll take a look at the code for the results page now.
Viewing the results of the survey
On the survey.php page, there is a button that can be clicked to View the Results.
If this button is clicked, the user will see something like this:
The lines represents how many people voted for a particular option. After that, we
have the number as a percentage, and what the option was.
Beginners PHP
–219–
On the previous page, survey.php, The HTML form was this:
<FORM NAME ="form2" METHOD ="GET" ACTION ="viewResults.php">
<INPUT TYPE = "Submit" Name = "Submit2" VALUE = "View results">
<INPUT TYPE = "Hidden" Name = "h1" VALUE = <?PHP print $qID; ?>>
</FORM>
The value in the variable $qID (part of the Hidden HTML form element) is
coming from the PHP code you saw earlier. This is the QID field that is in both the
questions and answers tables in our database. We need to pass this QID number
over to the viewResults.php page so that the correct results can be displayed.
If you open up the code for viewResults.php page (in the survey folder), you'll see
there's quite a lot there! But most of the code is taken up with manipulating the
red.jpg graphic! We're just stretching a red line, depending on how many votes
were cast for an option. The rest of the code pulls the data from the table, and puts
values into variables. We'll keep the two separate, for explanation purposes.
How many people voted for a particular option?
To see how many people voted for A, B or C, we first have to get that value from
the viewResults.php page.
if (isset($_GET['Submit2'])) {
$qNum = $_GET['h1'];
}
First, we check to see if the Submit button was clicked on the previous page. If it
was then we can GET the hidden value:
$qNum = $_GET['h1'];
The Hidden form element had the NAME "h1". It's this NAME that goes between
the square brackets of $_GET. The VALUE of the h1 hidden element is coming
from the $qID variable. This will be the QID field in the database tables
tblQuestions and answers. We can use this value to pull records from the tables,
which the next two lines do:
$SQL = "SELECT * FROM tblquestions, answers WHERE
tblquestions.QID = answers.QID AND answers.QID =
'$qNum'";
Home and Learn
–220–
$result = mysql_query($SQL);
Here, we're selecting all the records from two tables:
SELECT * FROM tblquestions, answers
But we need a WHERE part. The WHERE clause is quite tricky:
WHERE tblquestions.QID = answers.QID AND answers.QID = '$qNum'
To match the two QID fields, we have this:
tblquestions.QID = answers.QID
The name of the table goes first, followed by a dot. After the dot, we've typed the
QID field. This is present in both tables.
But we only need the records where the QID field matches the qNum that was
handed over from the previous page:
AND answers.QID = '$qNum'
We're saying "Only bring back the records where the two QID fields match AND
where the QID value in the answers table is equal to the value in the variable
called $qNum". A bit more complex, but go over it a few times and it will make
sense. Hopefully!
After the SQL has been run, we put the results into an array:
$db_field = mysql_fetch_assoc($result);
$question = $db_field['Question'];
$answerA = $db_field['A'];
$answerB = $db_field['B'];
$answerC = $db_field['C'];
$qA = $db_field['qA'];
$qB = $db_field['qB'];
$qC = $db_field['qC'];
If you look at the values in the square brackets, you'll see that they are the field
names from both tables. We're getting the value for the Question, the answers A, B
and C, as well as the original options for each questions (qA, qB and qC). All of
these values are then placed into variables, ready for displaying on the page.
Beginners PHP
–221–
We could just print the values to the page, like this:
print $question;
print $answerA;
print $answerB;
print $answerC;
But that's not very interesting for the viewer. Better is some form of graphic, like
the one below:
This is what you'll see when you click the button to View the Results. Here's how
it works.
Display a graphic for the results
At the top of the code, you'll notice some variables are set up:
$imgTagA = '';
$imgWidthA = '0';
$imgTagB = '';
$imgWidthB = '0';
$imgTagC = '';
$imgWidthC = '0';
$imgHeight = '10';
$totalP = '';
$percentA = '0';
$percentB = '0';
$percentC = '0';
Home and Learn
–222–
What we're going to do here is to manipulate the HTML IMG tag. This tag is used
to display an image, and ordinarily would look something line this:
<IMG SRC = 'red.jpg' HEIGHT = '10' WIDTH = '100'>
The part we want to manipulate with our PHP code is the WIDTH value. Instead
of setting it to a fixed value, we can set it to a value from the answers table.
In the answers table, the columns for A, B and C hold how many people voted for
a particular option. We have three separate IMG tags in our code, one for each of
the columns. If, for example, A held a value of 45 (meaning 45 people voted for
this option), we can make the WIDTH of the red line image 45 pixels.
Except, 45 pixels is not very wide. Much better to turn them all in to percentages.
Which is what the following code does:
$totalP = $answerA + $answerB + $answerC;
$percentA = (($answerA * 100) / $totalP);
$percentA = floor($percentA);
$percentB = (($answerB * 100) / $totalP);
$percentB = floor($percentB);
$percentC = (($answerC * 100) / $totalP);
$percentC = floor($percentC);
$imgWidthA = $percentA * 2;
$imgWidthB = $percentB * 2;
$imgWidthC = $percentC * 2;
First you need to total up how many people voted:
$totalP = $answerA + $answerB + $answerC;
Next, you can multiply A, B and C by 100 and then divide by the total:
$percentA = (($answerA * 100) / $totalP);
Because this would give an answer like 24.567, we can use the inbuilt Math
function floor to strip the "point something" at the end:
$percentA = floor($percentA);
Finally, you can multiply by, say, 2 to give the red line some extra width:
Beginners PHP
–223–
$imgWidthA = $percentA * 2;
The values in $imgWidthA, $imgWidthB and $imgWidthC can then be used to
build an IMG tag:
$imgTagA = "<IMG SRC = 'red.jpg' Height = " . $imgHeight . " WIDTH = " . $imgWidthA . ">";
To display this on the page, we use the following:
print $imgTagA . " " . $percentA . "% " . $qA . "<BR>";
So the red line gets displayed first, followed by the percentage of people who
voted for this option. A percent sign and the option itself complete the line.
And that completes the survey walkthrough. Feel free to adapt and amend the code
you downloaded. But don't forget to make a backup of the original files!
Next, we'll take a look at how to build your own online Forum.
Home and Learn
–224–
How to Build an Online Forum
In this section, you'll see what is involved in building a bigger web application, as
we take you through the coding for an online Forum. You may not want a Forum
on your site, of course, but the project is well worth doing all the same. There are
plenty of techniques here that can be carried over into your own pages, and
hopefully you'll acquire some new coding skills. There are plenty of exercises to
complete along the way, so it's not all theory!
This Forum, however, is not intended to be an application that you can simply
upload to your own site, and get working straight away. It is purely for teaching
purposes. All the files for this section can be found in the forum folder you
downloaded at the start of the book. Before you start, it's a good idea to make a
copy of this folder. That way, you won't be changing any of the original files.
Copy the entire forumfolder to the www directory on your server. You should
then have the forum folder inside of your www folder:
If you double click the forum folder, you'll see all the files and scripts mentioned
in this walkthrough. The database for this walkthrough can be found in the
Beginners PHP
–225–
databases folder, and is called dbforum. This folder contains the database for this
projects, and all the tables. Copy this folder the data folder of MySQL:
To check if everything is working, start your server and navigate to this address:
127.0.0.1/forum/forumTest.php
Or you can try this:
localhost/forum/forumTest.php
What you should see is this very basic forum:
Home and Learn
–226–
Obviously, the HTML needs improving! But this is one of things you'll be
changing, as we go along. You'll see where you can adapt the HTML, and how to
add your own code.
But the basics of the forum in the image above are common to most forums: you
have the forum sections as hyperlinks, and then additional information along side
each link. In our forum, we'll see how to get the number of posts in a section, and
how many people have replied to each post.
Once you have loaded the forum into your browser, play around with the it. Only
the Microsoft Word section is working, so click this link. You'll then see this:
Beginners PHP
–227–
What you're looking at is all the posts in the Microsoft Word section of the forum.
Only members are allowed to Post on the forum, and you'll see the member name
in the first column (Posted By). Only one Post has any replies – the first one at the
bottom. Click this link, and you'll see a new screen:
Home and Learn
–228–
Because there are 11 replies, they are split over 2 pages, with a link to each page.
If you were logged in as a member, you'd see a different link at the bottom of the
page, allowing you to reply to this Post. Try this for yourself. Click on the link that
says "Login Here". You'll be taken to an area that asks you to enter a username
and password. For this test forum, you can use any of the following logins:
Username Password
administrator admin101
newBoyJoined newboy
member5 member5
thisGirl thisGirl
thatGirl thatGirl
Login with one of the above, and you'll be allowed to Post topics in the Microsoft
Word section, and Reply to them.
Now that you have a good idea of how the forum works, it time to get started.
There's one important thing we need to do first: set up the database.
Setting up a Database for a bigger project
So far, the databases you have been constructing have been fairly simple. They
only consisted of one or two tables, and there wasn't much linking done between
each table. For this project, we'll need a more complex database. And lots of
tables!
To see what the database looks like, enter this address in your browser, if you have
Easy PHP version 1.8.
http://127.0.0.1/mysql/
If you have Easy PHP version 2.0, type this:
http://127.0.0.1/home/mysql/
This will open the phpMyAdmin page. On the left hand side, click the drop down
list for Databases. If you have copied the dbforum database over to the data folder
correctly, you should see it on the list:
Beginners PHP
–229–
Select dbforum from the list and you should see the tables in the database
displayed.
In this database, there are a massive 12 tables! But why so many?
The reason why there are so many tables is because we want to access the
information in the database as quickly as possible. You can get a real speed boost
by keeping data in different tables, rather than lumping all the information into one
or two tables. For example, we could have had one table to hold all the
information about the Microsoft Word section. We could have had columns for the
Posts, and columns for the replies. But this would mean that the one table would
be holding a lot of information: the text for the post, and the text for the replies. It's
much better (for coding and for speed) to keep posts and replies in separate tables.
Home and Learn
–230–
(When working on larger web projects, taking the time to plan your database, and
all the tables you'll need, will pay dividends. One thing you don't want to do is get
half way through your coding only to discover that your database isn't structured
correctly, and that you're going to need another table, or extra columns.)
As well as 10 tables for the posts and replies there is a separate table for the forum
sections, and a separate table for member information. Let's take a look at the
Forum Sections table first:
The Forum Sections Table
The Forum Sections table is the simplest table in the database. It consists of only
two fields. In phpMyAdmin, click on the forumsections table on the left hand
side. Then click on Browse, at the top. You should see this:
The two columns are sectionID, and sections. If you look at the main page of the
forum again, you'll see both the sectionID and the sections text in the status bar at
the bottom of the page:
Beginners PHP
–231–
The sectionID is at the end of the link: sID = secWP. The sections text is the text
for the hyperlink itself.
Exercise
In phpMyAdmin, click the Edit button (the pencil) next to secWP. From the page
that appears, change Microsoft Word into anything you like. Click the "Go"
button. Now, with Forum start page displayed in your browser, refresh your page.
What happens? You should see the text on the page change, as in the image below:
So the sections text in the Forum Sections table is used for the hyperlink on the
main page of the forum. The sectionID is used to identify which section of the
forum a visitor wants to go to. You'll see how that works soon. But have a look at
the members table now.
Home and Learn
–232–
The Members Table
The members table, as its name suggests, holds information about people who
have joined the forum. Click the members table in phpMyAdmin, then click
Browse at the top. You should see the columns in the table:
There are five columns in the members table: memberID, username, password,
signupDate, and email. (The passwords, by the way, should be encrypted. For
tutorial purposes, however, we haven't done this. But you saw how to do this in an
earlier section.)
The unique column (the primary key) is memberID. You'll see this column in the
other tables, as well. When you're displaying information about a Post or a Reply,
you'll want to include which member did the posting or replying. If you match the
memberID in, say, the wpposts table with the memberID in the members table,
you then have an easy and efficient way to display the member information. The
alternative is to include a username column in the posts and replies table. But this
would be a really bad way to construct a database, because you'd be duplicating
information. With a single members table, and a reference field in other tables, you
don't need to add username fields into every post and reply table. Just link to the
members table.
But the members table we have here is really basic. You could add more fields. A
common practice in Forums is to reward loyal members who Post and Reply often
with a higher status than other members. Its these members who keep a Forum
alive. Because they'll give up their spare time, it's a good idea to give them a little
control over the Forum, say as a moderator. In the members table, then, you can
add a Status field. This would allow you to change what a member is allowed to
do.
Depending on what type of forum you want, you can add even more fields to the
members section. What about adding an Avatar field? This could be a link to an
small image that the member wanted to use in their Posts and Replies. But we're
sure that you can think of more fields that can be added to our basic members
table!
Beginners PHP
–233–
The Post Tables
There are 5 Post tables in the database, one for each section of the forum. Here's
what each Post table is called, and what they are for:
wpposts - All posts to do with Microsoft Word
vbposts - All posts to do with Visual Basic .NET
xlposts- - All posts to do with Microsoft Excel
wdposts - All posts to do with Web Design
phposts - All posts to do with PHP
Since all of these tables have the same structure, we'll just take a look at the
wpposts table. Click on this table in phpMyAdmin, then click the Browse button.
You should see the following:
There are five fields in each of the post tables: threadID, memberID,
threadTopic, postText, and datePosted. Here's what they all do:
threadID - used to identify an individual post (the primary key)
memberID - used to identify which member posted this topic
threadTopic - the text used in the hyperlink when viewing the topics page
postText - the text for the Post
datePosted - the date the memebr Posted the topic
We'll access these post tables when a user clicks on a particular forum section on
the main page. When they do, this is what the user sees in the browser:
If you hold your mouse over a link, you'll see this in the status bar:
Home and Learn
–234–
The thing to notice about the link is rID=pos1. The pos1 is coming from the table,
and is the threadID field. Hold your mouse over a different link and you'll see the
pos1 change. When the link is clicked, we'll be pulling information from the reply
table. The reply table will also have a threadID field. We'll only be displaying
records where the threadID fields match.
The final five tables are for the replies.
The Reply Tables
There are 5 Reply tables in the database, one for each section of the forum. Here's
the table names, and a short description:
wpreplies - All replies for the Microsoft Word section
xlreplies - All replies for the Microsoft Excel section
phreplies - All replies for the Microsoft PHP section
vbreplies - All replies for the Microsoft Visual Basic .NET section
wdreplies - All replies for the Microsoft Web Design section
Again, all these tables have the same structure. So we'll just examine the wpreplies
table. In phpMyAdmin, click the wpreplies table on the left hand side. Then click
the Browse link at the top of the page. You should see the following:
Beginners PHP
–235–
There are five fields in this table: ID, threadID, memberID, reply, and
dateReplied. Here’s what they do:
ID - the primary Key. An auto incrementing number.
threadID - used to identify which post a member is replying to
memberID - used to identify which member replied to a post
reply - the text of the reply
dateReplied - the date the meber replied to the post
At the moment, the only Post to have any replies is pos1. That's why there are no
other values in this field. But if other posts have replies they would be labelled
pos2, pos3, etc. The threadID of the wpposts table is linked to the threadIDof
the wpreplies table. You can then say, "Select all the replies where there is a
threadID match."
The memberID field is also present in this table. This allows us to link to the
members table and display the username of the member who replied.
To get a clearer idea of how this database is structured, study the following list:
Table Name Field Names
forumsections sectionID sections
members memberID username password signupDate email
wpposts threadID memberID threadTopic postText
wpreplies ID threadID memberID reply dateReplied
These are the tables we'll be working with, when we do our coding. The
memberID is in three of the four tables above; the threadID is in two of the tables.
We'll be using these fields to link information. When you construct your own
Home and Learn
–236–
databases, it's important to consider which fields you can use to link information in
different tables. Planning like this can speed things up when you're pulling data
from your databases with PHP code.
Now that you have a decent grasp of just how the database is constructed, we can
take a look at the code.
Beginners PHP
–237–
The PHP code for the Forum
There are a lot more PHP pages for this project than there were for the other
projects you tackled. But the strategy that is used for this project is more or less
the same for all pages. Here's what we'll be doing:
€A user clicks on a link on a forum page
€The hyperlink will contain a variable that we can use to access our
database tables
€Take this code and pull records from the table
As an example, take the Microsoft Word Forum. You saw that the hyperlink in the
status bar is this, when you hold your mouse over it:
pageThread.php?sID=secWP
The page the user will be taken to is called pageThread.php. But we want to take
some information to this page (which forum the user asked for). This is done by
adding a question mark after pageThread.php. The question mark tells PHP that
there is some GET data to follow. You then type a variable name (sID, for us).
After an equals sign ( = ) you type what is going into the variable name (secWP, in
the hyperlink above).
When pageThread.php is loaded, we can grab that sID variable and do
something with it.
This, then, is the strategy we'll use for most of the forum – pass variables to other
pages by using GET data. We need to do this because there is no easy way to hand
variable information from one page to the next. You could write a cookie, or set up
some session variables. But the technique we're using is a common one, and is
widely used on the internet. There's a good chance you'll need to do this in your
own projects, so it's well worth learning.
To begin the forum walkthrough, we'll take a look at the main page of the forum –
forumTest.php. Off we go then!
The forumTest.php page
Load up the forumTest.php page in your browser by typing the following
address:
127.0.0.1/forum/forumTest.php
Home and Learn
–238–
You should see the main page of the forum. This one:
The address to type in your browser is:
127.0.0.1/forum/forumTest.php
Or
localhost/forum/forumTest.php
The HTML is, of course, not something you'd want on your own site – that table
looks far too basic! But the code is what we're interested in. Here's the coding
strategy:
€Get the number of posts in each forum
€Get the number of replies for each post
€Get the Forum main topics
€Build up some hyperlinks
Beginners PHP
–239–
€Print out a HTML table
The problem here is that we need to gain access to more than one table in our
database. The Forum main topics are in the table called forumsections, the posts
are in the table called wpposts, and the replies are in the table called wpreplies.
But the SQL is not too difficult, because we only need a limited amount of
information: how many forum sections there are, and what the link text should be;
a count of how many posts there are in each forum section; and a count of how
many replies there are in each forum section.
Bearing this in mind, open up the code for the forumTest.php page.
At first sight, it looks rather long and daunting. You'll see some comments in the
code, so as to break it down into manageable chunks.
The first eight lines of the code are just variables to hold the table HTML. This
sets the look and feel of the forum. In fact, you can make a start right away in
changing this!
Exercise
Even if your table HTML skills are a bit patchy, you can still change the colour
scheme. On line 7 of the code, you'll see this:
$tableHeaders = "<TR WIDTH = 200 height = 10 align = center
valign = middle bgcolor =#00EBEB>"
Change the bgcolor to anything you like. Try these, and see what happens:
#F84EFC
#402C3E
#74283E
What happened with the darker colours? Try a few colours of your own, and see
how you get on
Another thing you can change is the main cell colour. The cell colouring is done
with this line:
$tdStart = "<TD WIDTH = 200 height = 100 align = center
valign = middle bgcolor =#F84EFC>";
Again, change the bgcolor to anything you like. Start with the same colours as
above.
Home and Learn
–240–
Suppose you decided to go for one of the darker colours for the heading. How
would you change the font colour for the heading text? Can you see what you
would need to change? If you wanted white text, for example, the HTML would
be this:
<FONT COLOR = white>White Text</FONT>
Where in the PHP would you put the FONT tag?
Exercise
Using the colours above, change your table so that it looks like this one:
Ok, let's move on and examine the code.
After the table HTML, we set up some HTML for the hyperlinks:
$hrefStart = "<A HREF = pageThread.php?sID";
Beginners PHP
–241–
$hrefEnd = "</A>";
The important part here is the page we want to take the user to when a link is
clicked, and the part after php. The page we want to take the user to is
pageThread.php. But we're adding a question mark, and a variable name, as well:
?sID. We'll put something into the sID variable later. This will be the GET data
that we want hand to the page called pageThread.php. If you hold your mouse
over each link, you'll see this sID variable change. It will be one of five values:
secWP, secXL, secVB, secWD, and secPH. It's these values that we want to hand
over to pageThread.php.
The next 15 lines in the code set up some arrays. We want five arrays. They are:
$secIDs[] = array();
$tblPosts[] = array();
$tblReply[] = array();
$numPosts[] = array();
$numReply[] = array();
You'll see what they all do as we go along. But notice the two arrays called
$tblPosts[ ] and $tblReply[ ]. We've set these arrays up to hold the names of the
tables for the posts, and the names of the tables for the replies:
$tblPosts[] = "wpposts";
etc
$tblReply[] = "wpreplies";
etc
The technique we'll use is to loop round these tables, and get information from
each table.
The next six lines just get a connection to the database. You've met this code
before, so we won't go into it.
An if statement comes next, to see if a connection to the database has been found:
if ($db_found) {
}
You can add an else part to this, if you like. This should say what to do if the
database is not found. Print a simple "database not found" statement, for example.
The first code inside of the if statement is a for loop. We want to record how many
posts there are in each forum section, so we need to loop round each table and
count the number of rows in each post table. The for loop starts like this:
Home and Learn
–242–
for ($i = 1; $i < 6; $i++) {
}
The value of 6 is a hard-coded one. But this is not a good idea. Suppose you
wanted to add more sections to the forum. The code would break right here. A
better way to do this is use code to get how many rows there are in the
forumsections table. You would then use this number in the for loop. For teaching
purposes, though, we've stuck to a hard-coded value. We know there are only five
main sections in our forum, and we won't be adding any more!
To count how many rows there are in each of the post tables, the first line of the
for loop is this:
$SQL = "SELECT * FROM " . $tblPosts[$i];
We need some SQL to hand to PHP, and this is what the line does. The first value
we stored in the $tblPosts array was "wpposts". So the first time round the loop,
the SQL variable will hold this:
$SQL = "SELECT * FROM wpposts"
The next time round the loop, the SQL will be this:
$SQL = "SELECT * FROM wdposts"
Each time round the loop, the only thing that changes about the SQL is the name
of the table.
To count the number of rows in each table, we have this:
$result = mysql_query($SQL);
if ($result) {
$num_rows = mysql_num_rows($result);
$numPosts[$i] = $num_rows;
}
We pass the SQL to the inbuilt PHP function mysql_query( ). If any results are
found then the variable called $result will be true. We're testing for this in the if
statement.
If it is true, then next two lines will be executed:
Beginners PHP
–243–
$num_rows = mysql_num_rows($result);
$numPosts[$i] = $num_rows;
The first one just returns how many rows there are in a table. The second line puts
the number of rows into the array we set up earlier - $numPosts. When we come
to write our HTML for the hyperlinks, we'll use this array to print out how many
posts there are in each forum section.
The next few lines of the code are for the replies. We want to record how many
replies there are in each forum section. We do this in exactly the same was as for
the posts – just loop round the $tblReply array and execute some SQL. When the
loop is finished, the number of replies in each section is held in the array called
$numReply:
$numReply[$i] = $num_rows;
The next part of the code is a little bit trickier. We want to get the forum main
topics, and build up the links. We're doing both of those things inside of another
loop, a while loop this time. Here's the code:
$SQL = "SELECT * FROM forumsections";
$result = mysql_query($SQL);
$loopCount = 1;
while ($db_field = mysql_fetch_assoc($result)) {
$secIDs[$loopCount] = $hrefStart . "=" . $db_field['sectionID'] . ">" .
$db_field['sections'] . $hrefEnd;
$loopCount++;
}
The first two lines set up some SQL, and then execute that against the database.
The third line sets up a loop counter. We use this to access a different slot in the
$secIDs array. Then we have the while loop (actually, we should be testing to see
if $result is true, just like we did with the other two loops):
while ($db_field = mysql_fetch_assoc($result)) {
}
The variable $db_field will hold the array data that is brought back from
mysql_fetch_assoc($result). This inbuilt PHP function, if you remember, returns
an array. The array that is brought back is a row from our forumsections table.
(There are only two columns in this table.) The function will bring back data in
this format:
Home and Learn
–244–
Column_Name => Data
To access the data in the array, you can then do this:
$data = $db_field[Column_Name];
That's what the first line of the while loop does. It's a long line that spills over into
two on these pages:
$secIDs[$loopCount] = $hrefStart . "=" . $db_field['sectionID'] .
">" . $db_field['sections'] . $hrefEnd;
The part before the equals sign is this:
$secIDs[$loopCount]
$secIDs is the name of one of the arrays we set up at the top of the page. We want
to store the hyperlinks in this array. The hyperlink in $hrefStart was this:
$hrefStart = "<A HREF = pageThread.php?sID";
We're adding the sectionID after ?sID in the hyperlink above:
$hrefStart . "=" . $db_field['sectionID']
After this code executes, it would give you something like this:
pageThread.php?sID=secWP
To add the text for the hyperlink, we also have this in the while loop:
">" . $db_field['sections'] . $hrefEnd;
The right pointy arrow ( > ) completes the first part of the "A Href" HTML code.
The text for the link is then this:
$db_field['sections']
Finally, we add the rest of the HTML code for a hyperlink:
$hrefEnd
The last thing we do in the while loop is to increment the loop counter:
$loopCount++;
Beginners PHP
–245–
And that's the while loop! Yes, it's quite difficult. But study it for a while, and
you'll get there. Remember: all we want to do is to build up an array of hyperlinks.
Each hyperlink will be in this format:
<A HREF = pageThread.php?sID=secWP>Link Text</A>
The last thing we do in the forumTest.php code is to print out the HTML table.
Here it is:
print "<CENTER>";
print $TableStart;
print $tableHeaders;
for ($i = 1; $i < 6; $i++) {
print $RowStart;
print $tdStart . $secIDs[$i] . $tdEnd;
print $tdStart . $numPosts[$i] . $tdEnd;
print $tdStart . $numReply[$i] . $tdEnd;
print $RowEnd;
}
print $TableEnd;
print "</CENTER>";
The first line just prints out the HTML code to centre things (note the American
spelling). Then we have our two variables we set up at the top of the code. This
prints out the HTML for the start of a table, and prints out the formatted headings
we set up (these include the colour changes you made earlier).
Next, we have a for loop. What the loop does is to print out table code. It prints out
the row start tag (<TR>), and then some table data tags (<TD>). Inside of each
table data tag is the data from our three arrays $secIDs, $numPosts, and
$numReply.
The last line in the for loop prints out the row end tag (</TR>). After the loop has
finished, we print out the HTML for table end, and end the centre tag.
And that completes the code for the main page of our forum, forumTest.php.
Here's a summary of what we did:
€Set up some variables to hold HTML table information
Home and Learn
–246–
€Set up some arrays to hold information from the database tables
€Set up an array to hold all the hyperlinks
€Accessed the database, and returned the number of rows in the posts and
replies tables
€Returned the information about each forum section, and built up a
hyperlink
€Looped round and printed out the table, the hyperlinks, the number of
posts, and the numbers of replies
Exercise
Play around with the HTMl Table code, and see if you can improve things. If you
know any CSS, you can try to add that too.
Next, we'll take a look at the code for that page printed out in all the hyperlinks:
pageThread.php.
The pageThread.php page
When the user clicks on a forum section, they are taken to the pageThread.php
page. The page looks like this:
If you are logged in as a member, however, you'll won't see that text at the bottom.
You'll see this:
Beginners PHP
–247–
Only members are allowed to post topics and reply to others. The alternative is to
have an open forum where anyone can post and reply. But this opens the forum to
abuse, especially from people who want to spam your forum with lots of
hyperlinks advertising their own sites and wares.
The login part of the forum is more or less the same one you met in the first
walkthrough. But if you open up the code for pageThread.php (in the forum
folder), you'll see a variable near the top of the page called $nonMember. If
you're not logged in, the following text is added to the variable:
$nonMember = "YOU NEED TO BE LOGGED IN TO POST (MAKE
SURE COOKIES ARE ENABLED IN YOUR BROWSER)";
As an exercise, change this message to anything you like. Then reload the page to
see your new message.
If you are logged in as a member, the $nonMember variable will be blank. Later
in the code, an if statement will check what is inside of the $nonMember variable.
If it's blank, print the link to post a topic; if it's not blank, print the message.
After the session variable is checked, we have this line:
include 'forumHTML.php';
Here, we're including a file that holds all the HTML for the table, and a hyperlink.
Open this page up, and you'll see the same table code you met in the main forum.
The reason it's in a page of it's own is just to cut down on the amount of code in
the pageThread.php page. We could have done the same with the forumTest.php
page, but we thought we'd show you both techniques!
Exercise
Change the colours of the table headers for the Posts page, and the colours for the
cells in the table. Change the text in the headers to any colour you like.
Home and Learn
–248–
After the include file, we have a function called getPostSQL( ) and one called
getReplySQL( ). These are used to get some SQL, and you'll see how they work
soon.
But after the function, we have this:
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$secCode = '';
if (isset($_GET['sID'])) {
$secCode = $_GET['sID'];
}
}
Here, we're checking to see if the page in the browser was loaded via a hyperlink
click or a refresh (GET). If it was, there will be some GET information stored that
we can try to retrieve. We're setting up a variable called $secCode. This starts off
a being blank:
$secCode = '';
But if our variable from the previous page is set (the sID variable), we can return
this into the variable called $secCode. So $secCode is either going to be blank, or
it will have one of our five values: secWP, secXL, secVB, secWD, or secPH.
The next line is an if statement:
if ($secCode <> '') {
}
Here, we're checking if the variable called $secCode is not blank. Only if it's not
blank will the code for the if statement be executed.
If it is blank, then something went wrong. In which case, the code at the bottom
gets executed:
else {
print "Forum Not Available";
}
For the rest of the code, we need to do the following:
€Set up an array to hold all the posts
€Find out how many replies there are for each post
€Find out which member posted the thread
€Print the table out
Beginners PHP
–249–
€Print out the "login" link, or the "Non Member" information
There's quite a lot to do! Again, though, if you open up the code for
pageThread.php you'll see a lot of comments, breaking it down into manageable
chunks.
The first four lines to examine are these (the third line spills over into two, on
these pages):
$postData[] = array();
$replyHTML = "?sid=" . $secCode;
$replyHTML = "<A HREF = postForm.php" . $replyHTML .
">Create a new post</A>";
$forum = $secCode;
We set up an array called $postData[]. This will hold the information about each
post. The next two lines set up the "Create a new post" hyperlink. If the member
wants to create a new post, you need to pass in which forum section they want to
add the post for. Was it the Word section, the Excel section, the VB section, etc?
The only thing you need here is whatever is inside of the $secCode variable
(secWP, secXL, etc).
The fourth line just passes whatever is inside of the $secCode variable to a new
variable called $forum.
The next six lines connect to the database. After that, we have an if statement to
check if the database was found. This is the same code as before.
Set up an array to hold all the posts
Inside of the $db_found if statement, we have our first bit of code from our list:
Set up an array to hold all the posts.
The first line is this:
$secCode = getPostSQL($secCode);
This is a call to one of our functions at the top of the page. We're handing the
function whatever is inside of the secCode variable (getPostSQL($secCode) ).
The result of the function will be returned to the same variable ($secCode = ).
Home and Learn
–250–
If you study the function, you should be able to figure out what it does. But it's just
a series of if statements that check what is inside of $sectionCode. Is it secWP,
secWD, secVB, secXL or secPH?
Whichever one it is, some SQL gets returned:
$sql = "SELECT * FROM wpposts ORDER BY datePosted DESC";
The only thing that changes is which table we want to pull data from. But notice
the ORDER BY clause at the end. This is another SQL command you can use. It
sorts results based on a table column that you provide. Here, we want to sort the
results based on the datePosted column. We want a descending sort, so we've used
DESC. If you want an ascending sort, use ASC.
Exercise
Change DESC to ASC. Save the page, and reload it in your browser. Watch what
happens.
After we grab the SQL, we hand it to PHP for processing:
$result = mysql_query($secCode);
If any results are returned, the $result variable will be true. After setting a rows
counter to zero, we get the number of rows in a fourm section:
$totalRows = 0;
$totalRows = mysql_num_rows($result);
Next, we check how many rows were returned:
if ($totalRows <> 0) {
}
elseif ($totalRows == 0) {
print "This Forum is not yet available";
}
If the total number of rows is not zero, then the main code is executed. If no rows
were returned, we can print out an error message.
The first thing to get executed inside of the new if statement is a for loop:
for ($i = 0; $i < $totalRows; ++$i) {
Beginners PHP
–251–
$postData[$i] = mysql_fetch_array($result);
}
What we're doing here is looping round each row in a database table, and putting
the results into an array called $postData. But this is a new type of array –
something called a 2D array. Here’s how they work.
2D Arrays
In a normal array, each position can hold only one value. Like this:
$My_Array[] = array();
$My_Array[0] = 10;
$My_Array[1] = 20;
$My_Array[2] = 30;
So position 0 in the array above holds a value of 10, position 1 holds a value of 20,
and position 2 holds a value of 30.
But for us, we're returning a row of data from our table. Each row will be like this:
Column Name Value
threadID pos3
memberID mem1
threadTopic Clip Art
postText Got some good clip art?
datePosted 2006-04-13 12:11:06
In the post tables, there are 5 columns. When we use mysql_fetch_array( ) it will
fetch back each column name, and it's value. You can store all of this information
into an array of your own. But now, each position in the array will hold more than
one value. It will hold a row of data from the database table. The new array will be
like this:
$My_Array[0] = "pos3", "mem1", "Clip Art", "Got some good clip art?",
"2006-04-13 12:11:06"
So position 0 now holds more than one value. It holds 5 values, in the code above.
This is a 2D array – an array where each postion holds more than one value. (You
can also have a 3D array, but this is far more complex than we need.)
If you want to just access the datePosted value, you can do it like this:
Home and Learn
–252–
$postData[0]['datePosted']
So the name of you 2D array goes first, followed by square brackets. In between
the square brackets, you need a postion in the array. To access just a particular
value in that postion, you type a column name (or key value). In the line above,
we've specified the datePosted column.
If all that is a bit confusing, try this exercise.
Exercise
Add the following to the end of your for loop (the last line):
for ($i = 0; $i < $totalRows; ++$i) {
$postData[$i] = mysql_fetch_array($result);
}
print $postData[0]['threadTopic'] . "<BR>";
Refresh your page and see what happens. Now change the 0 to 1, save your work,
and refresh the page. Now change 'threadTopic' to 'datePosted'. Again, reload
the page. Try the other Column Names from the table above.
You can also add new keys and values to a 2D array. Simply type a new name in
between the square brackets, and its value. Like this:
$postData[0]['newValue'] = "new value here";
Exercise
Add this new for loop to your code:
print $postData[0]['threadTopic'] . "<BR>";
for ($i = 0; $i < $totalRows; ++$i) {
$postData[$i]['newValue'] = $i;
}
print $postData[0]['newValue'] . "<BR>";
Save your work, refresh the page, and watch what happens. Now change the 0 to
1, save your work, and refresh the page. What did you notice?
Beginners PHP
–253–
In summary: use a 2D array when you want each position in your array to hold
more than one value.
If you're still having problems grasping the concept of 2D arrays then think of
them like an Excel spreadsheet. Each row in the spreadsheet represents a postion
in the 2D array. Each column in the spreadsheet represents a value for each
postion. A normal array would look like this:
And a 2D array would look like this:
Back to the forum code (delete any code you added for the exercises above).
Find out how many replies there are for each post
We've just used a 2D array to store the row information from our database table.
Each postion in the 2D array will hold the threadID, the memberID, the
threadTopic, the postText and the datePosted. The next thing to do is find out how
many replies there are for each post. The code that does that is as follows:
$cnt = count($postData);
for ($i = 0; $i < $cnt; ++$i) {
$rep = $postData[$i]['threadID'];
$repSQL = getReplySQL($forum, $rep);
$result = mysql_query($repSQL);
$numRows = mysql_num_rows($result);
$postData[$i]['numRows'] = $numRows;
}
Home and Learn
–254–
First, we get a count of the number of positions in the 2D array. This is so that we
can loop through each postion. The first line in the for loop is this:
$rep = $postData[$i]['threadID'];
This returns the threadID from each position. We're using the variable $i to access
each postion in the array.
Next, we make a call the other function at the top of the code:
$repSQL = getReplySQL($forum, $rep);
The second function has two arguments, a section code ID (now stored in the
($forumvariable), and the threadID from the array. The function is again a series
of if statement. Depending on which forum section ID is being passed over, a SQL
statement is returned. Look at the SQL, though:
"SELECT * from wpreplies WHERE wpreplies.threadID = '$reply'";
We're saying, Select all the records from the wpreplies table where there is a
match on the threadID". The value in $reply is coming from our 2D array, and
will be something like pos1, pos2, po3, etc. This is from the Posts table. Because
of the way we set up our database, we have a threadID field in both the replies and
post tables. This is what allows us to link both tables in the above SQL.
After the SQL executes, it will return the number of rows where the two threadID's
are the same. This number is then stored into the variable called $numRows. The
final line of the for loop is this:
$postData[$i]['numRows'] = $numRows;
Here's we're adding a new key and a new value to our 2D array. The key is
between the second set of square brackets, and is called numRows. The value for
this key is whatever is inside of the variable called $numRows. This allows us to
store a record of how many replies there are in each posts.
Find out which member posted
The next thing we need to do is find out which member posted the original thread.
The code that does this is as follows:
for ($i = 0; $i < $cnt; ++$i) {
$memb = $postData[$i]['memberID'];
$memSQL = "SELECT * from members WHERE memberID = '$memb'";
Beginners PHP
–255–
$result2 = mysql_query($memSQL);
if ($result2) {
$db_field = mysql_fetch_assoc($result2);
$memName = $db_field['username'];
$postData[$i]['member'] = $memName;
}
}
The for loop uses the same variable that we set up to count the number of positions
in the 2D array. We're looping round each position in the 2D array and grabbing
the memberID. The line that does that is this:
$memb = $postData[$i]['memberID'];
When we set up the 2D arrray, one of the values that was returned from the table
was the memberID. We're storing this in a variable called $memb.
The next line is this:
$memSQL = "SELECT * from members WHERE memberID = '$memb'";
We're setting up some SQL here. Because we set up our database with a
memberID in three of the tables, we can select all the records where the
memberIDs match. Again, this shows you the benefits of planning your database
before you start!
The next few lines are these:
$result2 = mysql_query($memSQL);
if ($result2) {
$db_field = mysql_fetch_assoc($result2);
$memName = $db_field['username'];
$postData[$i]['member'] = $memName;
}
First, we run the SQL:
$result2 = mysql_query($memSQL);
Next, we have an if statement testing to see if the variable called $result2 is true.
If it is, the next few lines are executed. (We should really have an else part here, as
well. This should say what happens if $result2 is false.)
The first line inside of the if statement is this:
Home and Learn
–256–
$db_field = mysql_fetch_assoc($result2);
This brings back the result as an array. The array will return all the columns and
the data from the table row. This is then placed into the variable called $db_field.
The only thing we need is the username. So the line is this:
$memName = $db_field['username'];
We're placing the username in a variable called $memName. This is then added to
the 2D array:
$postData[$i]['member'] = $memName;
We now have a new key and value in our 2D array – member. This holds the
member's username. If you wanted to display other information about the member,
you would do it here. Get the email address, for example, or that Avatar we didn't
set up! You'd do it like this:
$email = $db_field['username'];
$postData[$i]['emailAddress'] = $email;
In other words, grab the column name from the table, and add a new key to the 2D
array.
Print the table out
The next thing to do is to print out all the information we stored in our 2D array.
We're printing it out in a table.
The technique is the same as the one in for the forumTest.php page - just print out
your HTML table headers, and loop round for the table rows and table data tags.
Here's just one line from the loop:
print $tdStart . $postData[$i]['member'] . $tdEnd;
We print out the TD start tag, and the TD end tag. In between that, we have this:
$postData[$i]['member']
To print out a value from the 2D array, just refer to its position in the array, and
the key you want to print. The position is coming from the loop ($i). The key is
member.
Beginners PHP
–257–
Examine the rest of the for loop that prints out the table. See if you can understand
what's going on. Especially this rather long line (split into three lines on these
pages):
print $tdStart . $hrefStart . "=" . $postData[$i]['threadID'] .
"&forum=" . $forum . "&pageID=0" . ">" .
$postData[$i]['threadTopic'] . $hrefEnd . $tdEnd;
An important part of the line above is this:
"&pageID=0"
As you may have realised, the whole line prints out the hyperlink. If you hold your
mouse over a hyperlink on the pageThread.php page, you'll see something like
this:
pageReply.php?rID=1&forum=secWP&pageID=0
This means that we are trying to pass three things to a page called pageReply.php.
We're trying to pass the following three variables:
rID
forum
pageID
The values in the variables are 1, secWP, and 0. You'll see how they work in the
next section. But the pageID is used to display the links that will take a user to say
page 1 of the replies, or page 2 of the replies (if there is a page 2), page 3, page 4,
etc. We're passing a value of zero because this is the first page of the replies.
The final part of the pageThread.php code is this:
if ($nonMember = = '') {
print "<P align = center>" . $replyHTML . "</P>";
}
else {
print "<P align = center>" . $nonMember . "</P>";
print "<P align = center>" . "<A HREF = login.php>Login Here</A>" . "</P>";
}
This just tests what is inside of the variable we set up at the top of the page. If
$nonMember is blank, then we can print out the hyperlink to allow the member to
post a new topic. If it's not blank, then we can display some HTML asking the user
Home and Learn
–258–
to login in. You can also add a link to register, if you like. We did this in a
previous section, so we won't cover it here.
But that's it! That's the code to display all the posts in your forum.
There is however, a problem. Supppose your forum is really large. If so, you'd
need to spread the posts over more than one page. That way a user can click onto
page 2 of the posts, page 3, etc. You'll see how to do this in the next section, which
explains how to write the code for displaying the replies to a post – we'll definitely
be needing that pageID!
The pageReply.php Code
The code for the pageReply.php page is a little bit longer than the others. This
page has to do the following:
€Check if the user is a member. If so, display a link so they can post a reply.
€Set up some functions to handle the SQL
€GET the post and the forum section that the user is replying to
€GET the pageID just in case there is more than 1 page of replies, allowing
us to set hyperlinks for each page
€Display information about the original post
€Display which member posted
€Find out which members replied
€Display all the replies, but limit them to ten replies per page
When a user clicks on a Post, they will see this page:
Beginners PHP
–259–
This is the page we're now going to examine.
The code that checks if the user is a member or not is the same code for the
previous section. After the functions, though, we need to GET the data that was
passed by the previous page. This is the data in the rID variable, the forum
variable, and pageID variable:
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$secCode = '';
$postID = '';
if (isset($_GET['rID'])) {
$postID = $_GET['rID'];
$secCode = $_GET['forum'];
$pageID = $_GET['pageID'];
}
}
Here, we're checking to see if the page was loaded using the GET method. If it
was, we first set a variable called $secCode and a variable called $postID to blank
strings. We then test to see if the rID variable has been set. If so, we can get the
information that was handed by the previous pages:
Home and Learn
–260–
$postID = $_GET['rID'];
$secCode = $_GET['forum'];
$pageID = $_GET['pageID'];
The code after that, you've already met in the previous section: Test to see if
secCode is blank, build up some HTML for the reply link, and open a connection
to the database.
If the database is found, we first need to find out how many people relied to a Post:
$repCode = getReplySQL($secCode);
$repCode = $repCode . "'" . $postID . "'";
$result = mysql_query($repCode);
$totalRows = mysql_num_rows($result);
First, we make a call to one of the functions at the top of the page. This returns
some SQL. The second line adds the postID to the SQL. When the SLQ is
executed on the third line, we'll have all the replies for a particular post. The forth
line tells us how many replies there are in total. We're putting this into a variable
called $totalRows.
If the $totalRows is not zero, then we can get some more SQL. Since we're only
going to be displaying ten links per pages, we can limit the data we pull from the
replies table. After all, there's no sense in getting all the replies, if we're not going
to be displaying all of them. To limit the number of replies, we have this:
$repCode = getReplySQL($secCode);
$repCode = $repCode . "'" . $postID . "'" . " LIMIT " . $pageID . ", 10";
The first line again makes a call to the functions at the top of the page. This gets
some SQL that we can use against the reply tables.
The second line is where we're building up some SQL to limit the number of
replies that will be pulled from the table. The first part of the second line just adds
the $postID to the SQL:
$repCode = $repCode . "'" . $postID . "'"
The rest of the line is where we're limiting the results:
LIMIT " . $pageID . ", 10";
The SQL command LIMIT, as its name suggests, allows you to limit the number
of results that you pull from a table. Take this SQL as an example:
Beginners PHP
–261–
SELECT * FROM tblReply LIMIT 0 10
The first number after LIMIT is which record from the table you want to start at.
The number zero means start pulling data from the first record in the table. The
second number says how many records you want to grab.
In our code, the start value is coming from the variable called $pageID. This is
passed to the code when a hyperlink is clicked. It started off as zero, if you
remember, because this will be the first page of results. If we wanted to start
pulling data from row number 11, as we do if there is more than 10 replies, then
we need to change the value in the variable called $pageID. This values gets
changed later, as you'll see. You can then add it to the hyperlinks.
We can then execute the SQL, and put the data from the table into an array:
$result = mysql_query($repCode);
$numRows = mysql_num_rows($result);
if ($result) {
for ($i = 0; $i < $numRows; ++$i) {
$replyData[$i] = mysql_fetch_array($result);
}
}
Notice how the loop goes from 0 to $numRows. Inside of the loop, we're putting
each row from the table into an array called $replyData.
But we also need to find out how many links are needed. If there are 11 replies to a
post, we need 2 links. Clicking the second link will take you to the second page of
replies. If we had 21 replies, we'd need three links – 10 on the first 2 pages, and 1
on the third. The code that counts how many links are needed is this:
$cnt = count($replyData);
$linkNum = floor($totalRows / 10);
The first line just counts how many replies are in the array. We pass this to a
variable called $cnt for use later in the code.
The next line divides the number of rows by 10. We use the floor( ) function to get
rid of any "point something" at the end. 11 divided by 10, for example, would give
us 1.1. We don't need the .1 at the end, so floor( ) will strip this off.
The next bit of code gets information about the thread:
$result = mysql_query($posCode);
$numRows = mysql_num_rows($result);
Home and Learn
–262–
if ($numRows = = 1) {
$db_field = mysql_fetch_assoc($result);
$topic = $db_field['threadTopic'];
$postText = $db_field['postText'];
$datePosted = $db_field['datePosted'];
$memPost = $db_field['memberID'];
}
We first execute the SQL we set up at the top of the code. This returns the original
Post. But we need to check if a row is returned. If a row is returned then we fetch
it back as an array:
$db_field = mysql_fetch_assoc($result);
The variable $db_field will then hold the fields from the Posts table. The next
four lines return the threadTopic, the posText, the datePosted, and the memberID.
These are all fields in the post tables. We then put theses into variables of their
own:
$topic = $db_field['threadTopic'];
$postText = $db_field['postText'];
$datePosted = $db_field['datePosted'];
$memPost = $db_field['memberID'];
We can then use these variables later in the code.
To find out which member posted the thread, we have this:
$memSQL = "SELECT * from members WHERE memberID = '$memPost'";
$result = mysql_query($memSQL);
if ($result) {
$db_field = mysql_fetch_assoc($result);
$postName = $db_field['username'];
}
This is the same code you met in the previous section. We use SQL to pull the
record from the members table WHERE there is a match on the memberID fields.
This is then placed into a variable called $postName.
To find out which members replied to the post, we have this code:
for ($i = 0; $i < $cnt; ++$i) {
Beginners PHP
–263–
$memb = $replyData[$i]['memberID'];
$memSQL = "SELECT * from members WHERE memberID = '$memb'";
$result2 = mysql_query($memSQL);
if ($result2) {
$db_field = mysql_fetch_assoc($result2);
$memName = $db_field['username'];
$replyData[$i]['member'] = $memName;
}
}
What we're doing here is looping round the $replyData array. This is the array we
set up earlier that holds information about the replies. We just want the memberID.
We then execute some SQL on the members table WHERE there is a match on the
memberID field. Once we find a match, we add a new key to the $replyData
array:
$memName = $db_field['username'];
$replyData[$i]['member'] = $memName;
The next thing we do is to print the links out, so that users can go to other pages.
As a reminder, here's the links we want to print out:
Hold your mouse over these links and you'll see this in the status bar:
Or this, for Page 1:
Home and Learn
–264–
The only thing to change here is the pageID. If you click Page 1, pageID is zero.
This is because you want to pull records 0 to 10 from the replies. For page 2,
pageID is 10. You can then use this number to pull records number 11 onwards.
Here's the code that does that:
$linkCount = 0;
$pageCount = 1;
for ($i = 0; $i <= $linkNum; ++$i) {
$linkPages = "<A HREF = pageReply.php?rID=" . $postID .
"&forum=" . $secCode;
$linkPages = $linkPages . "&pageID=" . $linkCount . ">Page " .
$pageCount . "</A>";
print $linkPages . " ";
$linkCount = $linkCount + 10;
$pageCount++;
}
The variable $linkNumhold the number of pages that are needed. What we're
doing here is looping round and creating links. The links are printed out with:
print $linkPages . " ";
But the two lines above this are where the hyperlinks get built. Study the code and
see if you can work out how it works. Compare the address in the status bar, with
the code in the loop. Here's the status bar (concentrate on everything after
pageReply.php):
And here's the two lines in the code that builds the link:
$linkPages = "<A HREF = pageReply.php?rID=" . $postID .
"&forum=" . $secCode;
Beginners PHP
–265–
$linkPages = $linkPages . "&pageID=" . $linkCount . ">Page " .
$pageCount . "</A>";
Finally, we can then print out the HTML table, using all the information we have
gathered so far. Again, study the code. You should, by now, be able to figure out
what's going on. But we're just looping round printing table data.
The only thing that remains now is to look at the code for posting a reply, and for
adding a new post to the forum.
We'll do that next.
The Reply Form
In the last section, there was a variable called $replyHTML. This is a hyperlink
that, when clicked on, leads to a page called replyForm.php. Here's the code:
$replyHTML = "?pid=" . $postID . "&sec=" . $secCode;
$replyHTML = "<A HREF = replyForm.php" . $replyHTML .
">Reply to this post</A>";
When the link is displayed, and the mouse held over the link, you'll see this in the
status bar at the bottom (you'll only see this link of you're logged in as a member):
The code above for the $replyHTML variable is adding the following after the
question mark:
pid=pos1
sec = secWP
When the link is clicked, we're passing these two variables to the page called
replyForm.php. The pos1 is which post the member wants to reply to, while the
Home and Learn
–266–
secWP is the forum section for Word Processing. When the member types the
reply, we'll use these values to update the database table.
So, open up the code for replyForm.php (in your forum folder), and we'll see how
it works.
(If you display the page in a browser, you'll see it's just a text area and a button.
The member types the reply, and clicks the button.)
The first bit of code is just the usual checks to see if the user accessing the page
has logged in. If they have, we grab the memberID, and put it in a variable:
session_start();
if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
header ("Location: login.php");
}
else {
$memberid = $_SESSION['memID'];
}
We also need to grab those variables from the previous page:
if ($_SERVER['REQUEST_METHOD'] = = 'GET') {
$secCode = '';
$postID = '';
if (isset($_GET['pid'])) {
$postID = $_GET['pid'];
$secCode = $_GET['sec'];
}
}
So the pid variable (the one that contained "pos1", from the previous page) is
handed over to a variable called $postID:
$postID = $_GET['pid'];
And the sec variable (the one that contained secWP) is handed to a variable called
$secCode:
$secCode = $_GET['sec'];
All the PHP code does is to print out HTML for a FORM. The form will contain a
textarea and a button. When the button is clicked, we'll process the data on another
php page. The ACTION attribue of the FORM tag is where the processing page is
located:
Beginners PHP
–267–
… METHOD ='POST' ACTION ='results.php'>";
We're going to be using the POST method to hand over our values to a page called
results.php. Notice that the FORM also has hidden values:
$hidSec = "<INPUT TYPE = Hidden Name = h1 VALUE =" . $secCode . ">";
$hidPost = "<INPUT TYPE = Hidden Name = h2 VALUE =" . $postID . ">";
$hidMem = "<INPUT TYPE = Hidden Name = h3 VALUE =" . $memberid . ">";
And there's our three variables: $secCode, $postID, and $memberid. When the
button on the form is clicked, these hidden variables will get handed over to the
page that processes the data – the results.php page.
Notice, too, that the NAME attributes for these hidden variables are h1, h2, and
h3. The NAME of the textarea on the form is post. We'll be passing all these
values to the processing page.
The results.php page
There's not too much code in the results.php page. All we need to do here is to
INSERT a reply to a post into the correct database table. Open up the code, and
we'll take a look at it.
The first thing to notice is the function at the top of the page – getReplySQL( ).
This takes one argument – the section code for the forum.
After the function, we check to see if the form was submitted using the POST
method:
if ($_SERVER['REQUEST_METHOD'] = = 'POST') {
}
If this returns a value of true, then we grab that data from the form:
$secID = $_POST['h1'];
$posID = $_POST['h2'];
$memID = $_POST['h3'];
$repText = $_POST['post'];
We're grabbing all those HIDDEN values from the form (which had the NAMES
h1, h2, and h3), as well as the text in the textarea (which had the NAME post).
The next three lines just add some single quotes. This is NOT how you'd want to
do it in your own forum! There are security issues here, because you're grabbing
text from a textarea and trying to INSERT it into a database. We covered the
security issues in an earlier section, but try this exercise:
Home and Learn
–268–
Exercise
Login to the forum with one of the username/passwords you saw earlier (these are
in the textfile called uandp.txt, in your forum folder). Reply to the post "A Brand
New Forum". You'll see this basic form:
If you just go ahead and click the button, the text Some text here should get added
to the database.
But surround the text with single quotes. Type this:
'Some text here'
Now click the button. You should see the message "No results". This is because
the code couldn't execute the SQL with those single quotes added. How would you
solve this? Review the section on security, especially the parts about SQL
injection attacks. Wasn't there something about magic quotes, and strip slashes?
How would you use these to lessen a SQL injection attack?
Another secrurity issue to worry about is how much text to allow the user to type
into the textarea. You can check how long a string is with the strlen( ) function. A
good run-down on how to use this can be found in the PHP manual here:
http://uk.php.net/manual/en/function.strlen.php
A simple way to use this would be:
$strCount = strlen($repText);
Beginners PHP
–269–
if ($strCount > 255) {
print "too many characters in your reply";
}
else {
//Do the rest of the code here
}
This just prints an error message if the user types in more than 255 characters.
(However, we've set the reply text field in the database tables to MEDIUMTEXT.
This can hold far more characters than 255. If you're restricting users to 255
characters, then TINYTEXT would be a better option.)
But back to our (less than secure) code. We've just grabbed the data from the
FORM and placed it into variables:
$secID = $_POST['h1'];
$posID = $_POST['h2'];
$memID = $_POST['h3'];
$repText = $_POST['post'];
The secID will contain something like "secWP", the posID will contain something
like "pos1", and the member ID is always "mem" plus a number (mem1, me2, etc).
The $repText variable holds the reply the user typed in the textarea.
The next code we have is some date code:
$date_today = date("Y-m-d H:i:s");
$date_today = "'" . $date_today . "'";
The characters we're using between the round brackets of the date function mean
we want the year first, then the month, then the day. These will be separated with
the "-" character. We're also adding a time part that returns Hours, Minutes, and
Seconds. The second line adds single quotes to the date, so we can use it in the
SQL.
The next line is a call to the function at the top of the page:
$tableSQL = getReplySQL($secID);
The function returns SQL to be used against the database table. But it only returns
part of the SQL we need:
$sql = "INSERT INTO wpreplies (threadID, memberID, reply,
dateReplied) VALUES ";
Home and Learn
–270–
In between the round brackets, we have the fields from the table. But we don't yet
have the VALUES we need to insert into these fileds. The next line in our code
adds the values. It's a long line that spills over into two on these pages:
$tableSQL = $tableSQL . "(" . $posID . "," . $memID . "," . $repText
. "," . $date_today . ")";
We’re building up the $tableSQL string variable here. It already holds the first
part of the SQL we need. We're now adding the VALUES. We need the round
brackets, the data from the variables, and the commas. After the line is executed,
the string would be something like this:
"INSERT INTO wpreplies (threadID, memberID, reply, dateReplied)
VALUES (pos1, mem1, "My Reply", "2006-10-22 13:30:14")"
After we open a connection to the database, we try to execute the query:
$result = mysql_query($tableSQL);
Then we check to see if the SQL is executed successfully:
if ($result) {
print "Your Reply has been added to the Forum." . "<BR>";
print "<A HREF = forumTest.php>Back to the forum</A>" . "<BR>";
}
else {
print "no results" . "<BR>";
}
And that's all we need to do on the this page: try to insert the reply into a reply
table in the database. Some of the error checking has been left out, so as not to
confuse the main techniques used. But you should implement the error checking in
your own code. Especially the checks to ward off attacks on your database!
Posting a Topic on the Forum
The final part of the walkthrough looks at how to allow users to post a new topic
on the forum. There is one useful database technique that may come in handy in
your own code – how to deal with primary key fields that are not auto-
incrementing numbers. Let's make a start.
The Post Form
The form that the user fills in to post a new topic is this:
Beginners PHP
–271–
As you can see, it's fairly basic, and you can definitely improve on this!
The form is similar to the Reply form, except for the addition of a text box. And
we're doing the same things in the code: hand over values to another php page for
processing. If you open the page called postForm.php, you can examine the code
for yourself.
Again, we're using the POST method to post the form data to a php page:
METHOD ='POST' ACTION ='resultsP.php'
The page we're posting the data to is called resultsP.php. We'll take a look at this
code in a moment, but notice the hidden variables: FILE REF
$hidSec = "<INPUT TYPE = Hidden Name = h1 VALUE =" . $secCode . ">";
$hidMem = "<INPUT TYPE = Hidden Name = h2 VALUE =" . $memberid . ">";
We want to hand over the forum section code (secWP), and the member id. The
text box on the form has been given the name tp, and the text area is called post.
With this in mind, take a look at the resultsP.php page (in your forum folder).
Home and Learn
–272–
The resultsP.php page
At the top of the code, there's two functions. We'll take a look at these later. But
bear in mind what this page does – inserts the new post into the database table.
(The security issues discussed in the previous section apply here, as well)
To get the data posted from the FORM, we have this:
$secID = $_POST['h1'];
$memID = $_POST['h2'];
$posTopic = $_POST['tp'];
$posText = $_POST['post'];
This is the same technique we used in the previous section: just put the POST data
into variables. The $secID variable will hold something like secWP, the $memID
variable will hold the member id, the $posTopic variable will hold the heading for
the topic, and the $posText variable will hold the text of the post itself.
After we get the connection to the database, we run in to our first problem. The
problem is that the Primary Keys in the post tables are not auto-incrementing
numbers. With an auto-incrementing number, you can usually leave the database
to update this field –all it needs to do is to add 1 to the previous value. Like this:
ID
0
1
2
3
If you update the table, the database would automatically add 1 to the ID field, and
the next row would be 4. You don't have to do anything.
But for the Primary Key in the post tables, we have a field called threadID. The
threadID field looks like this:
threadID
pos1
pos2
pos3
So you can't just add 1 to this field, if you insert a new row. You have to make
sure that the new row is pos4, and the next new row will be pos5, etc.
There's another problem as well. How can you be sure that the database hasn't
inserted your rows like this (and it will!):
Beginners PHP
–273–
threadID
pos1
pos3
pos2
So the last row in the table is pos2. If you try to update this with pos3 as the new
row, you'll get an error. Because there already is a pos3. A Primary Key field is
one that has unique values. And that why you'd get an error.
This is a common problem when you have your own format as the Primary Key in
a database table – adding a new unique value when that value is not an auto-
incrementing number.
In the example above, we need make sure that the new value in the threadID field
is pos4. This is a run-down on how we'll do it:
1. Get all the posts from the table
2. Set up an array to hold the threadID data
3. Strip the "pos" part, and just leave the number
4. Sort the array with the lowest number first and the highest last
5. Get the last value in the array (which will be the highest number)
6. Add 1 to this number
7. Put the "pos" part back
8. Update the threadID array
If you open up the code for the resultsP.php page, you'll see comments that tackle
the items in list above. The first part of the code gets all the posts from the table:
$SQL = getPostTable($secID);
This is just a call to one of the functions at the top of the page. When the function
is run, you'll have SQL like this:
"SELECT * FROM wpposts";
This selects all the records from a table called wpposts. The next two lines are
these:
$result = mysql_query($SQL);
$numRows = mysql_num_rows($result);
The first line executes the SQL. The second line returns how many rows we have
returned from table. We'll need this for the for loop. We then set up an array to
hold the threadID values:
Home and Learn
–274–
$posNums = array();
We now need to loop round the rows in the table, and get the threadID field:
for ($i = 0; $i < $numRows; $i++) {
$row = mysql_fetch_row($result);
$pID = $row[0];
$posNums[$i] = ltrim($pID, 'pos');
}
The loop goes from zero, to less than $numRows. The first line in the for loop is
this:
$row = mysql_fetch_row($result);
The inbuilt function mysql_fetch_row, as its name suggest, fetches a row from a
table. It will fetch it back with row[0] as the first table column, row[1] as the
second column, row[2] as the third, etc. Because we know that row[0] is our
threadID field, we can grab this value:
$pID = $row[0];
The treadID , then, is placed into a variable called $pID. To strip off the "pos" part
of the threadID, we have this:
$posNums[$i] = ltrim($pID, 'pos');
We're using the unbuilt function ltrim( ) to trim the "pos" part. In between the
round brackets, you type the text you want examine. After a comma, you type the
text you want trimming.
After the loop finishes, we might end up with something like this:
$posNums[]
1
3
2
So we have all the numbers in an array, but they are not sorted from lowest to
highest. The next line does that:
sort($posNums);
Beginners PHP
–275–
The inbuilt function sort( ) is used to sort the array. The name of the array you
want to sort goes between the round brackets of the function. But note that the
square brackets of the array go missing.
Once the array is sorted, we can get the last item in the array:
$lastID = end($posNums);
Again, we're using an unbuilt function. The end( ) function is used to move to the
last element of an array. Here, we're putting the value returned by the function into
a variable called $lastID.
Once we have the last number, increment it:
$lastID++;
Finally, once we have the last number, we can add the "pos" back on:
$threadid = 'pos' . $lastID;
All that coding gets us the highest pos number from our threadID field. We can
then go ahead an get the SQL for our INSERT statement:
$tableSQL = getPostSQL($secID);
This calls the function at the top of the page. The function will return something
like this:
$sql = "INSERT INTO wpposts(threadID, memberID,
threadTopic, postText, datePosted) VALUES "
We want to INSERT INTO the wpposts table a set of VALUES. The names of the
table columns go between the round brackets. But we still need to add the
VALUES. This is done with the rather long next line:
$tableSQL = $tableSQL . "(" . $threadid . "," . $memID . "," .
$posTopic . "," .$posText . "," . $date_today . ")";
We're just building up a string. Something like this:
INSERT INTO wpposts(threadID, memberID, threadTopic, postText,
datePosted) VALUES (pos1, mem1, "New Post", "This is the text", "2006-
10-22 13:30:14")
Once we have our SQL, we can try to run it:
Home and Learn
–276–
$result = mysql_query($tableSQL);
We can test to see if it is run successfully:
if ($result) {
print "Your Post has been added to the Forum." . "<BR>";
print "<A HREF = forumTest.php>Back to the forum</A>" . "<BR>";
}
else {
print "Couldn't add Post to the Forum";
}
If the code executes successfully, a new post will be added to the forum.
And that completes the code for Posting new topics. In fact that completes our
walkthrough of the entire forum! There is still work to be done, of course. So
here's a final Project for you to try.
Final Project
There is no form for a new member to sign up to the forum. Write the code for
this, and add links to the signup page in the rest of the forum. Here's a few things
you'll need to bear in mind.
€The Table is called members
€Primary key is in the format mem1, mem2, mem3, etc
€You'll need to build up string for your INSERT INTO SQL
€Use PHP to create the Form. Look at the code for replyForm.php and
postForm.php to see how to do this. You'll need to add textboxes for the
username and password, and one for the email address. The fields in the
members table are:
memberID
username
password
signupDate
email
€The form will need to be posted somewhere. You can create a new php
page for this. Add the SQL function, and the rest of the code, just like we
did above.
€You need to bear in mind that the Primary Key in the members table is just
like the threadID field, only with membefore the number instead of pos.
Beginners PHP
–277–
You'll have to code for this, to make sure you're adding a new row, and not
trying to overwrite an existing one
€To add the links to the signup page, you'll need to amend the code in a f ew
of the pages in the forum, such as pageReply.php. A simple hyperlink to
your new signup page should do
Play around with the rest of the forum, and see what you can come up with. At the
very least, you should be able to improve the look and feel of the forum. If you
know any CSS, you can always try to add some to the code.
Speaking of the code, any errors you need to correct in the forum? Most likely. In
a larger web application like this, you'll always find a bug or three! And don’t
forget to keep a copy of the origianl code.
But that completes not only the forum, but the whole beginners PHP book. We
hope you enjoyed it, and are motivated to take your new skills on to the next level.
Good luck!

Copyright: This Edition: Author:

Home and Learn/Ken Carney 2002 Revised and Updated - 2008 Ken Carney for Home and Learn All rights reserved

PHP Contents
WHAT IS PHP, AND WHY DO I NEED IT? ----------------------------------------------------------- 7 WHAT YOU NEED TO GET STARTED---------------------------------------------------------------- 7 INSTALLING AND TESTING EASY PHP ------------------------------------------------------------- 8
Troubleshooting------------------------------------------------------------------------------------------------------------------------15 Course Files -----------------------------------------------------------------------------------------------------------------------------15

WHAT IS A VARIABLE?--------------------------------------------------------------------------------- 17 PUTTING TEXT INTO VARIABLES ----------------------------------------------------------------- 19 VARIABLES - SOME PRACTICE --------------------------------------------------------------------- 20 MORE VARIABLE PRACTICE ------------------------------------------------------------------------ 24
Joining direct text and variable data----------------------------------------------------------------------------------------------25 Adding up in PHP ---------------------------------------------------------------------------------------------------------------------25

SUBTRACT, DIVIDE AND MULTIPLY-------------------------------------------------------------- 27 CONDITIONAL LOGIC ---------------------------------------------------------------------------------- 33
If Statements ----------------------------------------------------------------------------------------------------------------------------34 Using If Statements -------------------------------------------------------------------------------------------------------------------36 if … else Statements ------------------------------------------------------------------------------------------------------------------38 if … else if Statements ---------------------------------------------------------------------------------------------------------------39

MORE CONDITIONAL LOGIC ------------------------------------------------------------------------ 43
Comparison Operators ---------------------------------------------------------------------------------------------------------------43 NOT Equal To--------------------------------------------------------------------------------------------------------------------------44 Less Than and Greater Than -------------------------------------------------------------------------------------------------------45 Less Than or Equal To and Greater Than or Equal To ---------------------------------------------------------------------46 The Switch Statement ----------------------------------------------------------------------------------------------------------------47 Logical Operators----------------------------------------------------------------------------------------------------------------------49 Boolean Values-------------------------------------------------------------------------------------------------------------------------51 Operator Precedence – a List-------------------------------------------------------------------------------------------------------53

HTML FORMS---------------------------------------------------------------------------------------------- 54
The HTML Form ----------------------------------------------------------------------------------------------------------------------54 FORM Attributes ----------------------------------------------------------------------------------------------------------------------55 Method------------------------------------------------------------------------------------------------------------------------------------55 Post ----------------------------------------------------------------------------------------------------------------------------------------56 Action -------------------------------------------------------------------------------------------------------------------------------------56 Submit ------------------------------------------------------------------------------------------------------------------------------------57 Using PHP to get values from a HTML form ---------------------------------------------------------------------------------57 Getting values from a Text Box ---------------------------------------------------------------------------------------------------57 Checking if the Submit was clicked----------------------------------------------------------------------------------------------59 Setting the ACTION attribute to a different PHP page---------------------------------------------------------------------60 Keeping the data the user entered-------------------------------------------------------------------------------------------------62 How to handle other Form Elements with PHP-------------------------------------------------------------------------------64 Radio Buttons---------------------------------------------------------------------------------------------------------------------------64 Checkboxes------------------------------------------------------------------------------------------------------------------------------68

LOOPS -------------------------------------------------------------------------------------------------------- 74
For Loops --------------------------------------------------------------------------------------------------------------------------------74 A Times Table Programme ---------------------------------------------------------------------------------------------------------76 Code for the PHP Times Table ----------------------------------------------------------------------------------------------------77 While Loops-----------------------------------------------------------------------------------------------------------------------------80 Do While loops-------------------------------------------------------------------------------------------------------------------------81

The break statement-------------------------------------------------------------------------------------------------------------------82 For Each----------------------------------------------------------------------------------------------------------------------------------82

ARRAYS------------------------------------------------------------------------------------------------------ 83
What is an Array? ---------------------------------------------------------------------------------------------------------------------83 Setting up an Array -------------------------------------------------------------------------------------------------------------------83 Getting at the values stored in your arrays -------------------------------------------------------------------------------------87 Array - Using Text as Keys---------------------------------------------------------------------------------------------------------88 Arrays and For Each ------------------------------------------------------------------------------------------------------------------89 Sorting Array values ------------------------------------------------------------------------------------------------------------------90 Random Keys from an Array-------------------------------------------------------------------------------------------------------91 The count function --------------------------------------------------------------------------------------------------------------------91 Script One - Set up an array and print out the values -----------------------------------------------------------------------92 Script Two - Set up an array with your own Keys ---------------------------------------------------------------------------92 Script Three - Set up an array with mixed values ----------------------------------------------------------------------------93 Script four - Assign values to an array: Method Two example ----------------------------------------------------------93 Script Five - Looping round values in an array -------------------------------------------------------------------------------93 Script Six - Looping round values in an array: example 2-----------------------------------------------------------------94 Script Seven - Using text as Keys ------------------------------------------------------------------------------------------------94 Script Eight - Looping round an Associative array using For Each-----------------------------------------------------94 Script Nine - Sorting Arrays (Associative)-------------------------------------------------------------------------------------95 Script Ten - Sorting Arrays (Scalar) ---------------------------------------------------------------------------------------------95

STRING MANIPULATION ------------------------------------------------------------------------------ 97
Changing Case--------------------------------------------------------------------------------------------------------------------------97 Trimming White Space --------------------------------------------------------------------------------------------------------------98 Shuffle characters----------------------------------------------------------------------------------------------------------------------99 Finding one string inside of another-------------------------------------------------------------------------------------------- 100 Splitting a line of text--------------------------------------------------------------------------------------------------------------- 102 Joining text into a single line----------------------------------------------------------------------------------------------------- 104 PHP and Escaping------------------------------------------------------------------------------------------------------------------- 105 String function list------------------------------------------------------------------------------------------------------------------- 106

PHP FUNCTIONS ----------------------------------------------------------------------------------------- 111
What is a function?------------------------------------------------------------------------------------------------------------------ 111 Variable scope and functions----------------------------------------------------------------------------------------------------- 113 Functions and arguments ---------------------------------------------------------------------------------------------------------- 114 A Function to check for blank Textboxes ------------------------------------------------------------------------------------ 116 Getting values out of functions -------------------------------------------------------------------------------------------------- 118 By Ref, By Val ----------------------------------------------------------------------------------------------------------------------- 120 PHP Server Variables -------------------------------------------------------------------------------------------------------------- 122 HTTP Header() Function ---------------------------------------------------------------------------------------------------------- 123 Including scripts --------------------------------------------------------------------------------------------------------------------- 126

SECURITY ISSUES AND FORM ELEMENTS----------------------------------------------------- 128
htmlspecialchars() ------------------------------------------------------------------------------------------------------------------- 130 htmlentities()-------------------------------------------------------------------------------------------------------------------------- 131 strip_tags( )---------------------------------------------------------------------------------------------------------------------------- 132

WORKING WITH FILES IN PHP--------------------------------------------------------------------- 135
Opening a file------------------------------------------------------------------------------------------------------------------------- 135 Checking if the file exists --------------------------------------------------------------------------------------------------------- 141 Writing to files ----------------------------------------------------------------------------------------------------------------------- 141 Working with Comma delimited files (CSV files)------------------------------------------------------------------------- 143 Reading a text file line by line into an array – other options------------------------------------------------------------ 145 File Locations------------------------------------------------------------------------------------------------------------------------- 147

WORKING WITH DATE AND TIME FUNCTIONS IN PHP----------------------------------- 149
The date( ) function ----------------------------------------------------------------------------------------------------------------- 149 Day of the week Characters ------------------------------------------------------------------------------------------------------ 150

Month Characters-------------------------------------------------------------------------------------------------------------------- 150 Year Characters ---------------------------------------------------------------------------------------------------------------------- 150 Time Characters---------------------------------------------------------------------------------------------------------------------- 150 Other Date and Time Characters ------------------------------------------------------------------------------------------------ 151

PHP AND MYSQL----------------------------------------------------------------------------------------- 154
Creating a database using phpMyAdmin ------------------------------------------------------------------------------------- 156 Setting up Fields in your database tables ------------------------------------------------------------------------------------- 159 Adding records to a MySQL Table--------------------------------------------------------------------------------------------- 164

MANIPULATING A MYSQL DATABASE WITH PHP ------------------------------------------ 168
How to access a MySQL database with PHP code ------------------------------------------------------------------------ 168 Reading records from a database------------------------------------------------------------------------------------------------ 172 Structured Query Language ------------------------------------------------------------------------------------------------------ 174 Adding records to a database table --------------------------------------------------------------------------------------------- 177 Using HTML Forms with your Database------------------------------------------------------------------------------------- 180 Magic Quotes ------------------------------------------------------------------------------------------------------------------------- 181 SQL injection ------------------------------------------------------------------------------------------------------------------------- 182 Limit the charcters that a user can enter: ------------------------------------------------------------------------------------- 186

OTHER THINGS YOU CAN DO WITH SQL------------------------------------------------------- 187
Create a Table using SQL--------------------------------------------------------------------------------------------------------- 187 Updating a record in a table ------------------------------------------------------------------------------------------------------ 188 Deleting a record in a table ------------------------------------------------------------------------------------------------------- 189 Using WHERE to limit the data returned------------------------------------------------------------------------------------- 189

USER AUTHENTICATION WALKTHROUGH --------------------------------------------------- 191
The login page------------------------------------------------------------------------------------------------------------------------ 191 Checking if the user is logged on or not -------------------------------------------------------------------------------------- 197 Log Out--------------------------------------------------------------------------------------------------------------------------------- 198 Register a new user ----------------------------------------------------------------------------------------------------------------- 199 Other considerations ---------------------------------------------------------------------------------------------------------------- 202

BUILD YOUR OWN SURVEY APPLICATION---------------------------------------------------- 204
Set a Question for your Survey-------------------------------------------------------------------------------------------------- 204 The database -------------------------------------------------------------------------------------------------------------------------- 206 Setting a question – the code ----------------------------------------------------------------------------------------------------- 210 Add the Vote to the database----------------------------------------------------------------------------------------------------- 216 Viewing the results of the survey ----------------------------------------------------------------------------------------------- 218 Display a graphic for the results------------------------------------------------------------------------------------------------- 221

HOW TO BUILD AN ONLINE FORUM ------------------------------------------------------------- 224
Setting up a Database for a bigger project------------------------------------------------------------------------------------ 228 The Forum Sections Table -------------------------------------------------------------------------------------------------------- 230 The Members Table----------------------------------------------------------------------------------------------------------------- 232 The Post Tables ---------------------------------------------------------------------------------------------------------------------- 233 The Reply Tables -------------------------------------------------------------------------------------------------------------------- 234

THE PHP CODE FOR THE FORUM ----------------------------------------------------------------- 237
The forumTest.php page----------------------------------------------------------------------------------------------------------- 237 The pageThread.php page--------------------------------------------------------------------------------------------------------- 246 2D Arrays ------------------------------------------------------------------------------------------------------------------------------ 251 The pageReply.php Code---------------------------------------------------------------------------------------------------------- 258 The Reply Form---------------------------------------------------------------------------------------------------------------------- 265 The results.php page ---------------------------------------------------------------------------------------------------------------- 267 Posting a Topic on the Forum---------------------------------------------------------------------------------------------------- 270 The resultsP.php page -------------------------------------------------------------------------------------------------------------- 272 Final Project--------------------------------------------------------------------------------------------------------------------------- 276

.

But that would make it HPP.a server! Fortunately. The results are then handed over to you. But just a word for non-windows users. And. That's why PHP is so popular! But because PHP is a server-sided scripting language. PHP is known as a server-sided language.What is PHP. If you've come across a web page that ends in PHP. Over a million people have downloaded this software. create forums. and displayed in your browser.php). This allows you to test your PHP scripts on your own computer. which was called 'Personal Home Page Tools' ". and why do I need it? PHP is probably the most popular scripting language on the web. or make your computer pretend that it has a server installed. In fact. and a whole lot more.org . you won't be spending any extra money. We'll explain how to get it installed in a moment. we'll get you up and running. if you have a Windows PC (Win9x/Me/NT/2000/XP).) The most popular explanation of just what PHP stands for is "Hypertext Preprocessor". these tutorials assume that you have no programming experience at all. The results are then sent back to the client PC (your computer). That's because the PHP doesn't get executed on your computer. In fact. and where to get it from. there's one thing you'll need . but on the computer you requested the page from. you either have to get some web space with a hosting company that supports PHP.it's executed on the server. hopefully. surveys.marketing. picture galleries. you can do things like create username and password login pages. What you need to get started Before you can write and test your PHP scripts. . (You don't need to know any of these to make a start on PHP. We're going to be using some software called "EasyPHP". Other scripting languages you may have heard of are ASP. It is used to enhance web pages. Don't worry if this all sounds a little daunting . 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. This is because PHP is not run on your PC . surely? An alternative explanation comes from the emarketing network dictionary (http://www. it will be a lot easier than you think. then the author has written some programming code to liven up the plain. you don't need to go out and buy one. It installs everything you need. Python and Perl.nz/emarket_ dictionary. check details from a form.we've come across an easier way to get you up and running. and we prefer this version! They say: "The initials come from the earliest version of the program. old HTML. With PHP.

double click to install.tucows. First. It should look something like this: –8– .com/browse. You can get it from here (this site is nothing to do with ours.phpmac. we'd be interested in hearing from you! Installing and Testing EASY PHP OK. you need to download the software. as well as the link for Downloads.ch/software/macosx/ Another useful page is: http://farm.org/ Be sure to click the link for Installation Guide. If the installation goes well. Once you have downloaded the file. back to easy PHP and Windows.com/v1/instructions/install-php4x-for-apache1xx-onlinux.php?type=tut&cat=2 Linux Users There's quite a few sites out there to help Linux users get up and running with the Apache server and PHP. then try this guy's site to get up and running with PHP.html You can also have a look at this site: http://www.easyphp.php If you know any better ones.htm http://www. Here's two sites that are worth checking out: http://www.Home and Learn Apple Users If you have OS 10. The file you need to download is EasyPHP. The link to click on is "PHP Apache Module (NEW version 5)" http://www.e-gineer.phpfreaks.com/tutorials/12/0. you'll have an new entry on your Start > Programmes menu.entropy.com/blog/_archives/2004/7/20/108833. by the way): http://www.

But click Easy PHP from the menu and you'll get this popping up: If you get a green light for the Apache traffic sign. The Apache option on the configuration menu is an interesting one. We'll be using this in later tutorials. a red square will be flashing on and off on the letter "e". you can stop the server.Beginners PHP The newer version looks like this: Note that the older. and not the default one. From here. Pay attention to which version you have. more stable version is 1. they will then come from your location. because it matters. When Apache is running. and see the configuration pages. you'll see a black letter "e" in your system tray (in the bottom right of your screen. When your scripts are run. view help files.) When the Apache server is loaded up. The newer version is 2. exit it. Don't worry about it for now. Look for this line: –9– . where the clock is).8. then your server is up and running! (MySql is a database. as you’ll see below.0. you can change where your PHP files are stored. Right click to the letter "e" to see the following menu: From here.

type this instead: http://127. The hash (#) symbol before the old location means the line will be ignored. is the address of your own PC. need to test if your PHP pages are displaying OK.php Hit the enter key.1. Whenever you're testing your web pages. etc). Opera. however. But if you're not that adventurous.0. So.0.0. We'll now create a new folder in the root directory. If you have version 1. type a path to a directory of your choosing: #DocumentRoot "${path}/www" DocumentRoot "F:\myphp" In the example above. by the way.php If you have version 2.8 of EasyPHP.0.Home and Learn DocumentRoot "${path}/www" To change the location. start up your browser (Internet Explorer. and create a new PHP page. Then type a forward slash. and you should see a default index page: The address 127. To test it out.1/home/index. then you don't need to change anything! You do. we've changed the location to a folder on our "F" drive. Firefox. do the following: –10– . type the following into the address bar: http://127.0.1/index. type these numbers first.0.0. followed by the name of the PHP script you want to run.

You should then see an EasyPHP folder. Double click the folder called "EasyPHP1-8". or “EasyPHP 2. Here’s the files and folders for version 2.8. in our case. to see what's inside of it. double click the one where you installed EasyPHP to (The F Drive. You should see a list of files and folders. Probably "C".Beginners PHP €•On your desktop. and double click it.0b1”.0. You should see the following: If you have EasyPHP version 2. locate a folder called PHP. This is usually at C:\Program Files in XP. then you need to navigate to your Program Files folder.0: –11– . for you) If you have EasyPHP version 1. double click the icon for "My Computer" €‚When you see a list of all your drives.

This is the root folder mentioned on the index page above. Double click this folder to see the following: –12– .8: The folder we're looking for is called "www". which is in both versions.Home and Learn And here’s the folder view from version 1.

for version 2.Beginners PHP For version 1. But for both versions. do the following (in windows): €ƒClick File from then menu bar €„From the File menu. The PHP code just displays some information about PHP. click New > Folder €…Rename the folder to "test" (without the quotation marks) You now have a new directory (folder) in your root directory (the www one). If you've never used Notepad. or folders in this directory. Copy and paste the following script into a text editor.php file that you ran in your browser should appear. the index. click Start > All programmes > Accessories. except one line. This index file has now been moved to the home folder. Better yet. So you’ll just have a blank folder.0. You don't have to puzzle out what it all means.) <html> <head> <title>PHP Test</title> </head> <body> <?php phpinfo(). click Favorites > Add to favorites. Does it work? Save your new script to the "test" –13– .8. You'll then have a shortcut to this folder on your menu bar. The important part is. so it's a good idea to make a note of it. is just plain HTML. To create a new folder in your www folder. ?> </body> </html> Most of the script. (Something like Notepad will do. you'll be saving all of your scripts to this directory. then click Notepad. if you're a Windows user.

To test to see if it works. The /info.0. then try again: it means you didn't save it to the correct location. type the following address into your browser.php part means "look for a file called info.php.1/test/info.php.Home and Learn folder you created.8. you should be looking at the following page: –14– . If all went well. only the address in the address bar will be different.0. You should now have something like this in your folder view: If you can't see your new script in the test folder. For version 2. The image above is for EasyPHP version 1. and hit the enter key: http://127. Call the file info.php The /test means "look in a folder called test".0.

0.easyphp. try the following: €†Make sure you have copied and pasted the script exactly as it is above €‡If you can see the index. So it's time to make a start learning PHP.0.php page.1/test/info. as it's not our software. another way to refer to your own PC is with "localhost". try the help files at http://www. but you still can't see the PHP page above. you'll also need our Home and Learn Course files. then congratulations! Your PHP server is up and running.0. from now on . These can be downloaded from our website at the following address: –15– . we can't answer questions about EasyPHP.Beginners PHP If you saw the above page.php.php ok. We'll assume that everything is now up and running. You can use either 127.1 or localhost. though.) Course Files As well as getting your server up and running. Incidentally.it's up to you. then you'll need to start it.org/faq.php You should still see the same page. and with the file names exactly as they are above €ˆIf you can't see either page. The first thing you'll be learning is all about variables. and you can make a start scripting PHP pages. Try replacing this address: http://127. then make sure you have saved the script to the right folder. Good luck! Troubleshooting If you don't see the info. and apache is running.php3 (Unfortunately. If the Apache server is not running.0. but not the info. like we did above.php with this one: http://localhost/test/info. then make sure your Apache server is still running (can you see the black "e" with the red flashing square?). If it is running.

uk/downloads/downloads. Up first – variables.co. Good luck with your programming! –16– . If you have any problems downloading the files. and save the Zip file to your own hard drive.html Once on the page. please contact us at the following email address: enquiry@homeandlearn.homeandlearn.Home and Learn www. click the link for your course book.co.uk You can now make a start.

(There are some things your people balk at being called. You put things into your storage areas (variables) so that you can use and manipulate them in your programmes. If you're ok with the idea of variables. or a number. But most other characters are fine.) OK. These two people are going to be your storage areas. You can't begin their names with an underscore (_). They are going to be doing some work for you. Things you'll want to store are numbers and text. The man is going to be holding the coats. you have a bad memory. so your people (variables) now have name. But we can specify how many coats he will be holding. then you do the "telling" like this: mr_coats = 10 –17– . 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). You count how many coats you have. think of them like this. a man and a woman.Beginners PHP What is a Variable? A variable is just a storage area. then. The man and the woman. The question is. You count how many shoes you have. and give these to the woman. so you need to tell them what they will be doing. then you can move on. and then give these to the man. Suppose you want to catalogue your clothing collection. it's best to give them names that help you remember what it is they are holding for you. they could be called this: man_coats woman_shoes Or HimCoats HerShoes But because your memory is bad. are variables. Unfortunately. But it's no good just giving them a name. If you have ten coats to give him. If not. while you tally up what you own. If you like. They are going to hold things for you. which one of your people (variables) holds the coats and which one holds the shoes? To help you remember. You enlist two people to help you.

You add up in PHP like this: $total_clothes = $mr_coats + $mrs_shoes. Remember. The next thing to check is if you've missed out a dollar sign. So it would be this: $mr_coats = 10 If you miss the dollar sign out. you're learning PHP. Holding the number 10. (The equals sign. But don't worry about it.a semi-colon. –18– . The answer will then get stored in our new variable. If you get any parse errors when you try to run your code. actually. so there's something missing. the first thing to check is if you've missed the semi-colon off the end. then your people will refuse to work! But the other thing missing is something really picky and fussy . First. the one we've called $total_clothes. 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. So it will work out the total for you. You can also add up like this: $total_clothes = 10 + 35. But back to our people (variables). It's very easy to do. We can do the same thing with the other person (variable): $mrs_shoes = 25. Lines of code in PHP need a semi-colon at the end: $mr_coats = 10. by the way. After the equals sign. you tell your variable what it will be doing.Home and Learn So. Just remember that you need the equals sign to store things in your variables. the variable name comes first. If we then wanted to add up how many items of clothes we have so far. It's called an assignment operator. If you use a plus sign. and $mrs_shoes is holding a value of 25.) However. at this stage. So the man is holding ten coats. is not really an equals sign. then an equals sign. Two things. $mr_coats is holding a value of 10. and can be frustrating. your people (variables) need a dollar sign at the beginning (people are like that). in our case. PHP thinks you want to add up. $mrs_shoes is holding a value of 25. So.

however.PHP will see plus signs and then add things up.Winter Coats. Are they Winter coats? Jackets? Summer coats? You decide to catalogue this. But you can't do this: $coats1 = 'Winter Coats". The equals sign follows the variable name. So. But notice the double quotation marks around our text. you can add up more than two items: $total_clothes = 10 + 35 + 7 + 38 + 1250. You do it in a similar way to storing numbers: $coats1 = "Winter Coats". Putting Text into variables You can also put text into your variables. then you'll get errors. The direct text will then get stored in the variable to the left of the equals sign. You can put direct text into your variables. –19– . Of course. Suppose you want to know something about the coats you own. We can store other text in the same way: $coats2 = "Jackets". $coats3 = "Summer Coats". So you can do this: $coats1 = 'Winter Coats'. and on the next few pages you'll see how they work in practice. You can. our variable name starts with a dollar sign ($). however. You use these storage areas to manipulate things like text and numbers. In the above line. to recap. use single quotes instead of double quotes. variables are storage areas. After the equals sign. we've started with a single quote and ended with a double quote. we have direct text . The answer is then stored in your variable name. the one to the left of the equals sign. PHP will see the plus sign and add the two together for you. as well. Again.Beginners PHP Again. We've then given it the name coats1. You'll be using variables a lot. If you don't surround your direct text with quotation marks. But the idea is the same . This will get you an error.

php Or this: http://localhost/variables.Some Practice In the previous section. ?> </body> </html> When you've finished typing it all.php.0.php If you've created a folder inside the www folder. we'll take a look at how to display what's in your variables.0. you saw what variables are: storage areas to hold things like numbers and text. type the following. start your browser up and type this in the address bar: http://127. You tell PHP to remember these values because you want to do something with them.0. because it's the one we'll be building on. So see if you can get this script working first. Testing variables with PHP First.Home and Learn Variables . save the page as variables. But you learn more by typing it out yourself . as explained at the start of the book. you'll get some practice using variables.0. if you prefer. Off we go.1/FolderName/variables. save it to the WWW folder. (You can copy and paste it. or your PHP software. Then Run the script. In this section.php –20– . Using a text editor like Notepad. To run the page.1/variables. then the address to type in your browser would be something like: http://127.it doesn't really sink in unless you're making mistakes!) <html> <head> <title>Outputting text</title> </head> <body> <?php print("It Worked!"). We're going to be viewing our results on a web page. Remember: when you're saving your work.

?> –21– . A red square will be flashing. you should have seen the text "It worked!" displayed in your browser. It will be the letter "e". the line of code ends as normal . We'll try some text first. You can put as much space as you like between the opening and closing syntax. type another question mark. Finally.with a semi-colon (. it needs some help. go between the HEAD section of an HTML page. but change your PHP from this: <?php print("It Worked!"). Browsers recognise PHP by looking for this punctuation (called syntax): <?php ?> So you need a left angle bracket ( < ) then a question mark ( ? ). If you're printing direct text. make sure that your server is up and running. ?> To this: <?php print("It Worked!"). If so. Scripts can also. type PHP (in upper or lowercase). We've put the PHP in the BODY section of an HTML page. You can also write your script without any HTML. After the question mark. if the server is running. Let's examine the PHP in more detail. Finally. you need a right angle bracket ( > ). To display things on the page. After your script has finished. Congratulations! You have a working server up and running! (If you weren't successful. You have to tell it what kind of script it is. just type the variable name (including the dollar).) The PHP script is only one line long: <?php print("It Worked!"). Keep the HTML as it is. 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. ?> The rest of the script is just plain HTML code. If you're using easyPHP.). But before a browser can recognise your script.Beginners PHP If you were successful. we've used print( ). you should see an icon in the bottom right of your screen. To print what's inside of a variable. What you want the browser to print goes between the round brackets. and often do. then you need the quotation marks (single or double quotes).

it's clear that there's only one line of code . print($test_String). Don't run your script yet. ?> --------------TESTING VARIABLES-----------Use this type of comment if you want to spill over to more than one line.. print("It Worked!"). After the equals sign. So add this second line to your code: <?php $test_String = "It Worked!". Another way to add a comment. ?> Comments in PHP are for your benefit.Home and Learn 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. is like this: <?php /* */ $test_String = "It Worked!". the text "It Worked!" has been added. Notice how the comment begin and end. Then add some comments . you can type anything you like.Print. ?> We've set up a variable called $test_String. Change the Print line to this: print($test_String). They help you remember what the code is supposed to do.. –22– . <?php //--------------TESTING VARIABLES-----------$test_String = "It Worked!". After the two slashes. print($test_String). This tells PHP to ignore the rest of the line. A comment can be added by typing two slashes. The line is then ended with a semi-colon. Now.

Did it have any effect? Put a single quote at the beginning of your text. What happens when you run the code? Exercise Delete the dollar sign from the variable name. And you might be thinking . you'll be better able to correct your errors. and a double quote at the end. Then run the script again. It's a big step: your coding career has now begun! Exercise Change the text "It Worked!" to anything you like. we'll do some more variable work in the next section. and test it out. Now that you're up and running. but now delete the semi-colon.what's the big deal? Well. this time? It's well worth remembering these errors . –23– . Especially if you have to send your code to someone else! But you can now run the script above. Exercise Change the double quotes to single quotes. What error did you get? Put the dollar sign back. Try typing some numbers in between your double quotes.you'll see them a lot when you're starting out! If you see them in future. what you just did was to pass some text to a variable. How did you get on? You should have seen that exactly the same text got printed to the page.Beginners PHP Whichever method you choose. Run your code again? What error did you get. make sure you add comment to your code: they really do help. Then run your code. and then have PHP print the contents of the variable. instead of text.

php: <html> <head> <title>More on Variables</title> </head> <body> <?php print ("Basic Page"). Run your script again. To see why. print ($first_number). you get the variable name! TIP: We recommend you use single quotes for your direct text. let's try some numbers. With double quotes. Start with the basic PHP page again. Remember: if you're printing direct text then you need quotation marks. You outputted text to a page. Now that you can print text to a page. Then change the print line to this: print ("$first_number"). Did it make a difference? What did you expect would print out? Now change the double quotes to single quotes. if you're printing a variable name then you leave the quotes out. run the first script above. and learn how to do your sums with PHP. and NOT double quotes . ?> </body> </html> We'll now set up a variable and print it to the page. In this section.Home and Learn More Variable Practice In the previous section. add double quotation marks around your variable name. the number 10 still prints. you'll do some more work with variables. ?> All the code does is to print the contents of the variable that we've called $first_number. So change your code to this: <?php $first_number = 10. with single quotes. In other words. you started to work with variables.there's fewer hassles if you do! –24– . and save your work as variables2.

When we're printing the contents of both variables. ?> This time. Try the new script and see what happens. Suppose you want to print out the following "My variable contains the value of 10". Now delete the dot and then try the code again. The full stop (period or dot. Run the code. In PHP. to some) is used for this. but just included in the Print statement. print ('My variable contains the value of ' . $first_number). a full stop is used to separate the two. Adding up in PHP OK.Beginners PHP Joining direct text and variable data You can join together direct text. you can do it like this: <?php $first_number = 10. Try out the above script. let's do some adding up. you just separate each variable name with a plus symbol.) To add up the contents of variables. Any errors? You can also do this sort of thing: <?php $first_number = 10. $direct_text = 'My variable contains the value of '. the direct text is not inside a variable. Try this new script: –25– . To add up in PHP. the plus symbol (+) is used. and whatever is in your variable. $first_number). ?> So now we have two variables. Again a full stop is used to separate the direct text from the variable name. and see what happens. try changing the full stop to a plus symbol. The new variable holds our direct text. and see what happens. (If you still have the code above open. What you've just done is called concatenation. print ($direct_text .

the one we've called $sum_total. –26– . PHP knows what is inside of the variables called $first_number and $second_number. which we've called $sum_total. This script is a little more complicated than the ones you've been doing. To print out the answer. because we've just told it in the two line above! It sees the plus symbol. The addition to the right of the equals sign gets calculated first ($first_number + $second_number). $second_number = 20. To the right of the equals sign. The total of the addition is then stored in the variable to the left of the equals sign ($sum_total =). $sum_total). It puts the answer to the addition in the variable to the left of the equals sign (=). If you're a bit puzzled. Try this exercise. print ($direct_text .Home and Learn <?php $first_number = 10. ?> In the above script. The important line is this one: $sum_total = $first_number + $second_number. A third variable is then declared. You can. $sum_total). of course. $sum_total = $first_number + $second_number. and assigned a value to it: $second_number = 20. add up more than two numbers. then adds the two values together. just remember what it is we're doing: adding the contents of one variable to the contents of another. we've used concatenation: print ($direct_text . we've added a second number. we've added up the contents of the first variable and the contents of the second variable: $sum_total = $first_number + $second_number. $direct_text = 'The two variables added together = '.

First up is subtracting. Assign a value of 30 to your new variable. and run your code: $sum_total = $second_number . –27– . simply use the minus sign (-). Subtract. (In other words. Instead of the plus sign (+). Put the sum total of all three variables into the variable called $sum_total. Subtraction To add up using PHP variables. $second_number = 20. Change your $sum_total line to this. 20. $sum_total = $first_number + $second_number. print ($sum_total). add up 10.use the plus symbol (+) to add up. print ($number + 30).$first_number. Divide and Multiply 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. You can do this: print (10 + 20 + 30). you did this: <?php $first_number = 10. Or even this: $number = 10. and 30!) You don't have to use variable names to add up.Beginners PHP Exercise Add a third variable to your code. ?> Subtraction is more or less the same. Use concatenation to display the results. But the point is the same .

To clarify what you mean. and then add the 10? Or did we mean add up 10 and 20. Try them both in your code. $second_number = 20. Here's an example: <?php $first_number = 10. the reason might be the way we set out the sum. of course. ?> The answer you should get is 70. you can subtract more than one number at a time. $second_number = 20.$first_number. $sum_total = $third_number . You can also mix addition with subtraction. But note where the parentheses are: –28– . print ($sum_total). PHP knows what is inside of the variables called $second_number and $first_number. get the answer 10. Try this: <?php $first_number = 10.Home and Learn The s$sum_total line is more or less the same as the first one. Just like addition. It knows this because you assigned values to these variables in the first two lines. $sum_total = $third_number . Except we're now using the minus sign instead (and reversing the two variables). print ($sum_total). and puts the answer into the variable on the left of the equals sign. Did we mean 100 . ?> Run the code above. When PHP comes across the minus sign. Here's the two different versions of the sum. We then use a print statement to display what is inside of the variable. When you run the script you should.$second_number . $third_number = 100. then take it away from 100? The first sum would get 90.20.$second_number + $first_number. you can use parentheses in your sums. 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. but the second sum would get 70. $third_number = 100. Again. it does the subtraction for you.

$sum_total = $second_number * $first_number. $second_number = 20. In PHP. you can multiply more than two numbers: <?php $first_number = 10. Here's some code for you to try: <?php $first_number = 10. print ($sum_total).Beginners PHP Version one $sum_total = ($third_number . we're just multiplying whatever is inside of our two variables. This means that you'll get answers that are entirely unexpected! As we'll find out right now.$second_number) + $first_number. some operators (Math symbols) are calculated before others. print ($sum_total). the * symbol is used. it means multiply 20 by 10. $third_number = 100. That way. Version two $sum_total = $third_number . just to clarify what you want PHP to calculate. PHP and Multiplication To multiply in PHP (and just about every other programming language). If you see 20 * 10. $second_number = 20. We're then assigning the answer to the variable on the left of the equals sign. $sum_total = $third_number * $second_number * $first_number. ?> –29– . It's always a good idea to use parentheses in your sums. ?> In the above code.($second_number + $first_number). you won't get a peculiar answer! Another reason to use parentheses is because of something called operator precedence. (You can probably guess what the answer is without running the code!) Just like addition and subtraction.

See if you can guess what the answer is before trying it out: <?php $first_number = 10. and then multiplies these two numbers first. Multiplication and division are thought to be more important that addition and division. It does this first: $second_number * $first_number. In our sum above. we're using parentheses to make sure that PHP does the multiplication first. the plus sign. It doesn't do this first: $third_number + $second_number This makes the parentheses more important than ever! Use them to force PHP to work out the sums your way. it will move on to the other symbol. Try them both: Version one $sum_total = $third_number + ($second_number * $first_number). THEN the addition is done. When it gets the answer to the multiplication. When it works out the answer. we're using parentheses to make sure that PHP does the addition first. In version one. But try this code. some operators (Math symbols) are calculated before others in PHP. THEN the multiplication is done. PHP will work out the sum between the parentheses first.Home and Learn And you can even do this: $sum_total = $third_number * $second_number * 10. Here's we're using parentheses to force two different answers. ?> 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. and then move on to the other operator. $second_number = 2. So these will get calculated first. print ($sum_total). $sum_total = $third_number + $second_number * $first_number. Then it moves on to the addition. Version two $sum_total = ($third_number + $second_number) * $first_number. $third_number = 3. Here's the two different version. PHP sees the * symbol. –30– . When it gets the answer to the addition. In version two.

–31– .$second_number. Here's the two versions for you to try: Version one $sum_total = $third_number . ?> Again.$second_number) / $first_number. If you see 20 / 10. $second_number = 20. The first version will get you an answer of 98. Try it yourself: <?php $first_number = 10.($second_number / $first_number).Beginners PHP PHP and division To divide one number by another. it means divide 10 into 20. $third_number = 100. ?> PHP won't work out the sum from left to right! Division is done before subtraction. Try this code: <?php $first_number = 10. So this will get done first: $second_number / $first_number And NOT this: $third_number . but the second version gets you an answer of 8! So remember this: division and multiplication get done BEFORE subtraction and addition. print ($sum_total). Using parentheses will clear things up. Version two $sum_total = ($third_number . $sum_total = $third_number . Use parentheses if you want to force PHP to calculate a different way. print ($sum_total). you have to be careful of operator precedence. $second_number = 20. the / symbol is used in PHP.$second_number / $first_number. $sum_total = $second_number / $first_number.

You don't need any special syntax to set these types of numbers up. Use a print statement to output your answer. 45. Exercise Use variables to calculate the answer to the following sum: (200 * 15) / 10 Use a print statement to output your answer. though: you shouldn't trust them. print ($sum_total).5 and 10. 134. Exercise Write a script to add up the following two numbers: 15.5. Then subtract the answer from 100. like 0.2.Home and Learn Floating point numbers A floating point number is one that has a dot in it. A warning comes with floating point numbers. here's a few exercises (In your print statements.8. $second_number = 2. subtract. –32– . Here's an example for you to try: <?php $first_number = 1. $sum_total = $second_number + $first_number. ?> You add up. Use a print statement to output your answer. really precise answer! To round up this section on number variables. if you're after a really. 76. there should be no numbers – just variable names): Exercise Write a script to add up the following figures: 198. divide and multiply these numbers in exactly the same way as the integers you've been using.

You can then makes decisions based on what is inside of the variable. You are asking. will it make me happy?" "If I study this course. When you press a button labelled "Don't Press this Button . "Well. think about the username again. you use the "IF" word like this: if ($User_Name == "authentic") { //Code to let user access the site here. If you have stored a username in a variable. for example." In PHP. will the neighbours be pleased?" "If spend all my money on a new pair of shoes. To help you do the checking. the if statement looks like this: if ( ) { } –33– . You might have a variable like this: $User_Name = "My_Regular_Visitor".. } Without any checking. will it improve my web site?" Conditional Logic uses the "IF" word a lot.. what happens IF I do press the button?" You use Conditional Logic in your daily life all the time: "If I turn the volume up on my stereo. then let $User_Name have access to the site. Conditional Logic is all about asking "What happens IF . you use Conditional Logic to test what is inside of a variable. ". You want to ask: "IF $User_Name is authentic. You would use some Conditional Logic to test whether or not the variable $User_Name really does contain one of your regular visitors. something called Conditional Logic comes in very handy indeed. For the most part. you'll then need to check if this is a valid username. The text "My_Regular_Visitor" will then be stored inside of the variable called $User_Name.Under any circumstance!" you are using Conditional Logic.Beginners PHP Conditional Logic You saw in the last section that variables are storage areas for your text and numbers. As an example. But the reason you are storing this information is so that you can do something with them.

a UK keyboard. To test a variable or condition. These are just to the right of the letter "P" on your keyboard (Well. You need the left curly bracket first { and then the right curly bracket } at the end of your if statement. { The first one has the curly brackets the wrong way round (should be left then right). (This lesson continues on from our introduction to Conditional Logic---WEB SITE ONLY) You can use the print statement to "print out" HTML code. { And so will this: if ($User_Name == "authentic") { //Code to Let user access the site here. take the following HTML code to display an image: <IMG SRC =church. } To clarify things. anyway). you type the condition you want to test. while the second one has two left curly brackets. let's have a more practical example. Get them the wrong way round. This will get you an error: if ($User_Name == "authentic") } //Code to Let user access the site here. If Statements In this lesson.curly ones.jpg> –34– . You also need some more brackets . here. you start with the word "if". In between the two round brackets. and PHP refuses to work. we're testing to see whether the variable called $User_Name has a value of "authentic": ($User_Name == "authentic") Again.Home and Learn You can see it more clearly. 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) { //your code here. we'll use if statements to display an image on the page. In the example above. You then have a pair of round brackets. As an example.

Now fire up your server. you'll need an image called church. But you can put that code inside of the print statement: print ("<IMG SRC =images/church. When you run the code. the image should display. You can find these amongst the files you downloaded at the start of the book. in the folder called images.jpg>").Beginners PHP Just plain HTML. and in a folder called images. Then try the following script: <?PHP print ("<IMG SRC =images/church.jpg>"). Copy this images folder to your www (root) directory. Hopefully. ?> Save your script to the same folder as the images folder (though NOT inside the images folder). and give it a try. –35– . you'll see the church image display. as in the following graphic: Let's use that same line of code above to illustrate if statements.jpg. Of course.

we want to test if it has a value of 1. If the user selected "kitten". If the user selected "church". The first two lines just set up some variables: $kitten_image = 1." To complete the first line of the if statement we have another round bracket. then display the kitten image. So we need the double equals sign (= =). Then we have our if statement. and save it as testImages. After the word "if" we have a round bracket. Here's some code: <?PHP $kitten_image = 1. We want to test what's inside of this variable.php. then display the church image. and you'll probably get the dreaded parse error! –36– . What we want to say is: "If the variable called $kitten_image has a value of 1 then execute some code. Here it is without the print statement: if ($kitten_image == 1) { } Notice how there's no semi-colon at the end of the first line . The double equals sign doesn’t really mean “equals”. if ($kitten_image == 1) { print ("<IMG SRC =images/kitten. Miss any of these out. $church_image = 0. Let's look at the code and see what's happening. A value of 1 has been assigned to the variable called $kitten_image. It means “has a value of”.jpg>").Home and Learn Using If Statements We can use an if statement to display our image. Specifically. Then comes our variable name: $kitten_image. and a left curly bracket. the kitten image should display. (Notice how there's no HTML!) When you run the script.you don't need one. } ?> Type that out. $church_image = 0. A value of 0 has been assigned to the variable called $church_image.

so that our kitten image will display. That code prints out the HTML for the church image: –37– . This goes inside of the if statement: if ($kitten_image == 1) { print ("<IMG SRC =images/kitten. you can just do this: if ($kitten_image == 1) { print ("<IMG SRC =images/kitten. if ($kitten_image == 1) { print ("<IMG SRC =images/kitten. however. The new if statement is just the same as the first. then the code inside of the if statement gets executed.jpg>"). 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. PHP doesn't care about your spaces. PHP doesn't bother reading the rest of the if statement. $church_image = 1. } ?> Notice that the $kitten_image variable now has a value of 0 and that $church_image is 1. but acceptable! To make use of the church image. here's some new code to try: <?PHP $kitten_image = 0. But if your if statement only runs to one line..jpg>"). is the print statement. Not very readable. though.jpg>"). ". "If the variable called $kitten_image has a value of 1 .. When you run the script.jpg>"). keep everything on one line. so it's perfectly acceptable code. the church image will display. } You need the semi-colon at the end of the print statement. } if ($church_image == 1) { print ("<IMG SRC =images/church. That's because of this line: if ($kitten_image == 1) { That says. because $kitten_image has a value of 0.Beginners PHP The code we want to execute. } In other words.

. the left and right curly brackets are used. you’ll see that you have a normal If Statement first. an if … else statement is being used. followed by an “else” part after it. You should find that the church image displays in the browser. you type the code you want to execute. Let’s see how it works.jpg>"). however. we set up two variables: $kitten_image = 0.jpg>"). Like this: <?PHP $kitten_image = 0.jpg>"). } ?> Copy this new script. save your work.Home and Learn print ("<IMG SRC =images/church. if ($kitten_image == 1) { print ("<IMG SRC =images/kitten.. –38– . and try it out. In our code. Here’s the “else” part: else { } Again. else statement. } else { print ("<IMG SRC =images/church. This time. if … else Statements Instead of using two if statements. The syntax for the if else statement is this: if (condition_to_test) { } else { } If you look at it closely. $church_image = 1. $church_image = 1. we can use an if . In between the curly brackets.

“ For us. PHP ignores the line of code for the if statement. The first line of the if statement tests to see what is inside of the variable called $kitten_image. run the code between the else curly brackets. Because a value of “not true” has been returned (false. The syntax is this: else if (another_condition_to_test) { } Change your code to this. $church_image = 0.Beginners PHP The variable called $kitten_image has been assigned a value of 0. $church_image = 1. 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. Change your two variables from this: $kitten_image = 0. $church_image = 0. and the variable called $church_image has been assigned a value of 1. –39– . Run your code again and watch what happens. You should see the kitten! But can you work out why? if … else if Statements You can also add “else if” parts to your If Statements. so PHP sees this as not true. To this: $kitten_image = 1. Instead. if you like). to see how else if works: <?PHP $kitten_image = 1. that was this: else { print ("<IMG SRC =images/church. 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 the church image gets displayed.jpg>"). It’s testing to see whether this variable has a value of 1.

jpg>"). } What you’re saying is “If the previous if statement isn’t true. But notice the “else if” lines (and that there’s a space between else and if): else if ($church_image == 1){ print ("<IMG SRC =images/church. then try this one. If it’s false (the $church_image variable does NOT holds a value of 1). then the line of code will be ignored. then the code between the new curly brackets gets executes. else if. } else { print ("No value of 1 detected"). $church_image = 0. But change your two variables from this: $kitten_image = 1. 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. } else if ($church_image == 1){ print ("<IMG SRC =images/church.Home and Learn if ($kitten_image == 1) { print ("<IMG SRC =images/kitten.jpg>"). one for each condition that you want to test. If it’s true (the $church_image variable holds a value of 1). –40– . To catch any other eventualities. Notice that all parts (if. we have an “else” part at the end.jpg>").” PHP will then try to evaluate the new condition. } ?> Here’s we’re just testing to see which of our variables holds a value of 1. and PHP will move on.

Then run your code again. But examine the code for the script (ignore the HTML form tags for now). What do you expect to happen? As a nice example of if statements. –41– . What it does is to display an image. Copy this to your own www (root) folder.php” in the files that you downloaded. they should display.Beginners PHP to this: $kitten_image = 0. there is a file called “selectPicture. If statements are being used to test what is inside of a single variable. $church_image = 0.php" method="post"> <select name="picture"> <option value="none">Select a Picture</option> <option value="church">Church</option> <option value="kitten">Kitten</option> <option value="planet">Planet</option> <option value="cartoon">Cartoon</option> <option value="space">Space Image</option> <option value="abstract">Photoshop Abstract</option> </select> <input type="submit" name = "Submit" Value = "Choose an Image"> </form> <?PHP if (isset($_POST['Submit'])) { $picture = $_POST['picture']. Here’s the entire script: <html> <head> <title>PHP Test</title> </head> <body> <form Name = "f1" action="selectPicture. It’s in the scripts folder. As long as you have all the images mentioned in the script. based on what the user selected from a drop down list.

To help you along. Since you will be using if statements a heck of lot in your coding career. } else if ($picture == "kitten"){ print ("<IMG SRC =images/kitten. it’s essential that you have a good grasp of how to use them. We’re then displaying the image that corresponds to the word held in the variable.jpg>"). } else if ($picture == "planet"){ print ("<IMG SRC =images/planet. } else if ($picture == "space"){ print ("<IMG SRC =images/stellar.jpg>").jpg>"). All we’re doing is testing what is inside of the variable called $picture. } } ?> </body> </html> Don’t worry too much about the rest of the code: concentrate on the if statements. } else { print ("No Image to Display"). } else if ($picture == "cartoon"){ print ("<IMG SRC =images/cartoon.Home and Learn if ($picture = = "church") { print ("<IMG SRC =images/church.jpg>"). } else if ($picture == "abstract"){ print ("<IMG SRC =images/abstract. there’s some about Conditional logic! –42– .jpg>").jpg>").

You used if. and else. There a few more of these “operands” to get used. If you were testing for a genuine username. Comparison Operators Operand == != < > <= >= Example Meaning $variable1 = = $variable2 Has a value of Has the same value as $variable1 != $variable2 Does NOT have a value of … Does NOT have the same value as" $variable1 < $variable2 Less than $variable1 > $variable2 Greater than $variable1 <= $variable2 Less than or equals to $variable1 >= $variable2 Greater than or equals to Here’s some more information on the above Operands. you need the exclamation mark/equals sign combination ( != ). and then we’ll see a few examples of how to use them. the variable called $variable1 is being compared to the variable called $variable2 if ($variable1 = = $variable2) { } != You can also test if one condition is NOT the same as another. else … if. “If what the user entered is NOT the same as the value in the variable called $username then print something out.Beginners PHP More Conditional Logic You saw in the last section how to test what is inside of a variable. –43– . for example. In which case. you could say: if ($what_user_entered != $username) { print("You're not a valid user of this site!") } The above code says. Take a look. In the example below. The double equals sign is known as a Comparison Operator. Here’s a list. == The double equals sign can mean “Has a value of” or "Has the same value as”. You used the double equals sign (= =) to test whether the variable was the same thing as some direct text.

$what_visitor_typed = ‘logMEin’. The rest of the If Statement is exactly the same format as you used earlier. so we’ll start with “NOT equal to”.Home and Learn < You'll want to test if one value is less than another. Use the left angle bracket for this ( < ) > You'll also want to test if one value is greater than another. if ($what_visitor_typed != $correct_username) { print("You're not a valid user of this site!"). Use the right angle bracket for this ( > ) <= For a little more precision. You’ve already used the double equals sign. the letters “ME” are in uppercase. they are in lowercase. The things you’re trying to compare need to be different before a value of true is returned by PHP. Use the left angle bracket followed by the equals sign ( <= ) >= If you need to test if one variable is greater than or equal to another. In the second variable ($what_visitor_typed). use the right angle bracket followed by the equals sign ( >= ) We’ll now run through a few examples. So the two are not the –44– . You should be able to guess what it does! But the thing to note here is the new Operator. and add the following script: <?PHP $correct_username = ‘logmein’. you can test to see if one variable is less than or equal to another. in the first variable. Instead of using the double equals sign we’re now using an exclamation mark and a single equals sign. NOT Equal To Create a new PHP file for this. } ?> Save your work and try it out.

$discount_total = 100. if ($total_spent > $discount_total) { print("10 percent discount applies to this order!"). $what_visitor_typed = 'logmein'. Change your script to this (new lines are in bold text): –45– . Try this script: <?PHP $total_spent = 110. what will get printed out? Less Than and Greater Than The Less Than ( < ) and Greater Than ( > ) symbols come in quite handy.Beginners PHP same. If they do. the text will get printed. They are really useful in loops (which we'll deal with in another section). Before you run the script. } else { print("Welcome back. if ($what_visitor_typed != $correct_username) { print("You're not a valid user of this site!"). } ?> By using the great Than symbol ( > ). we're saying "If the total spent is greater than the discount total then execute some code. } See if you can figure out what has changed. Suppose you wanted to test if someone has spent more than 100 pounds on your site. friend!"). Change your script to this: $correct_username = 'logmein'. Because we used the NOT equal to operator. The Less Than and Greater Than symbols can be used." The Less than symbol can be used in the same way. you want to give them a ten percent discount. and for testing numbers in general.

Less Than or Equal To and Greater Than or Equal To We can use the same code above to illustrate "Less Than or Equal To" and "Greater Than or Equal To". $discount_total = 100. Now run your code again. Change this line in your code: else if($total_spent < $discount_total) { to this: else if($total_spent <= $discount_total) { –46– . and no errors occurred. } ?> In the else if part added above. We're only checking to see if the two variables are either Less Than ( < ) each other. to this: $total_spent = 100. Instead of adding yet another else if part. is because we haven't written any condition logic to test for equality. } else if($total_spent < $discount_total) { print("Sorry – No discount!"). We need to check if they are the same (as they now are). we can use <= or >=. or Greater Than ( > ) each other. Here's how. Did anything print? The reason why nothing printed. Notice that the $total_spent variable has been reduced to 90. if ($total_spent > $discount_total) { print("10 percent discount applies to this order!"). checking to see if the two totals are equal.Home and Learn <?PHP $total_spent = 90. we're checking to see if the total spent is Less Than ( < )100 pounds. If it is. Change this line in your code: $total_spent = 90. then a new message is display.

Exercise Suppose you want to apply the discount if 100 pounds or more has been spent. you'll be glad to hear that there's even more of them! Before we get to them. depending on the value inside of the variable. so that we can display the correct picture.) Now run your code again. It's this direct text that we want to check. case 'church': print('Church Picture'). but are well worth the effort. –47– . then execute the code. break. if you have only one variable to test. let's take a look at another logic technique you can use – the Switch Statement. Use the >= symbol for this exercise. To see how switch statements work. A long list of if and else … if statements were used.Beginners PHP (The only thing that's changed is the Less Than or Equal to symbol has been used instead of just the Less Than sign. A different picture was displayed on screen. The Switch Statement In some earlier code. Change your code above to display the correct message. is to use something called a switch statement. study the following code: <?php $picture ='church'. The operands can take a little getting used. } ?> In the code above. We want to know what is inside of the variable. If you're having a hard time with all these Operands. break. we tested a single variable that came from a drop-down list. switch ($picture) { case 'kitten': print('Kitten Picture'). we place the direct text "church" into the variable called $picture. A better option." So the text gets printed to the screen. Because we're now saying "If total spent is Less Than or equal to discount total.

A sort of "catch all" option. you'll see something else you can add to your own code: default: print ("No Image Selected"). } It looks a bit complex. //code here After the semi colon on the 'case' line. you type the name of the variable you want to check. options. After the round brackets. you'll get an error if you miss out any semi-colons at the end of your lines of code! break. you need a left curly bracket. PHP will simply drop down to the next case and check that. unknown.Home and Learn To test a single variable with a Switch Statement. a list of values was coming from a drop-down list. It’s in the scripts folder. the following syntax is used: switch ($variable_name) { case 'What_you_want_to_check_for': //code here break. Needless to say. –48– . To see the Switch statement in action. so we'll break it down. case 'What_you_want_to_check_for': The word 'case' is used before each value you want to check for. It's used when there could be other. These value were: church and kitten. Inside of the round brackets. there is a file called "selectPicture2. After the the text or variable you want to check for. if you like! If you look at the last few lines of the Switch Statement.php"amongst the ones you downloaded at the start of the book. Try out. You need to tell PHP to "Break out" of the switch statement. among others. These are the values we need after the word 'case'. switch ($variable_name) { You Start with the word 'Switch' then a pair of round brackets. you type the code you want to execute. a colon is needed ( : ). If you don't. Use the word 'break' to get out of the Switch statement. In our code. The default option is like the else from if … else.

there's also something called Logical Operators. too. You typically use these when you want to test more than one condition at a time. but NOT both? Is at least one value true? Is NOT something The new Operands are rather strange.Beginners PHP Logical Operators As well as the comparison operators you saw earlier. After all. if ($username ='user' && $password ='password') { print("Welcome back!"). $password ='password'. The && Operand The && symbols mean AND. Use this if you need both values to be true. } The if statement is set up the same. so here's a closer look. if you're meeting them for the first time. Operand && || AND XOR OR ! Example $variable1 && $variable2 $variable1 || $variable2 $variable1 AND $variable2 $variable1 XOR $variable2 $variable1 OR $variable2 !$variable1 Meaning Are both values true? Is at least one value true? Are both values true? Is at least one value true. you could check to see whether the username and password are correct from the same If Statement. For example. you don't want to let people in if they just get the username right but not the password! Here's an example: $username ='user'. but notice that now two conditions are being tested: $username ='user' && $password ='password This says. though. Both conditions need to go between the round brackets of your if statement. } else { print("Invalid Login Detected"). Here's the table of these Operands. as in our username and password test. then let them in". A couple of them even do the same thing! They are very useful. "If username is correct AND the password is ok. The | | Operand –49– .

AND and OR These are the same as the first two! AND is the same as && and OR is the same as ||. For example. If they are both false. incidentally. then the code gets executed. then PHP will move on. We touched on this when we discussed variables. you can simply replace this: $username ='user' && $password ='password With this $username ='user' AND $password ='password And this: $total_spent =100 || $special_key ='SK12345' With this: $total_spent =100 OR $special_key ='SK12345' It's up to you which you use. Else they don't get any discount. Logical Operators have a pecking order. suppose you want to grant a discount to people if they have spent more than 100 pounds OR they have a special key. if ($total_spent =100 || $special_key ='SK12345') { print("Discount Granted!"). } else { print("No discount for you!"). $special_key ='SK12345'. There is a subtle difference. Use this symbol when you only need one of your conditions to be true. but as a beginner. The full table is coming soon! –50– . OR is a lot easier to read than ||. as well. earlier. } This time we're testing two conditions and only need ONE of them to be true. AND is a lot easier to read than &&. is to do with Operator Precedence. If either one of them is true.Home and Learn The two straight lines mean OR. The difference. You'd then code like this: $total_spent =100.

"If $test_value is false then set it to what it's NOT. You set them up just like other variables: $true_value = 1. It's an XOR situation! $contestant_one = 'best ears'. if it's been set to false. A Bit confused? It's a tricky one. if ($test_value == false) { print(!$test_value). but it can come in handy! Boolean Values A Boolean value is one that is in either of two states. } See if you can guess which of the two will print out. Here's some code to try: $test_value = false. and vice versa. then PHP sees the expression as false. } The code above will print out the number 1! (You'll see why when we tackle Boolean values below.Beginners PHP XOR You probably won't need this one too much. you want to reset a variable to true. The ! Operator This is known as the NOT operator. –51– . $contestant_two = 'best teeth'. then the value is true. True is usually given a value of 1. so it will now get this value. Only one of them can win. You use it test whether something is NOT something else. } else { print("Only one winner!"). But it's used when you want to test if one value of two is true but NOT both. Suppose you had to pick a winner between two contestants. and False is given a value of zero. You can also use it to reverse the value of a true or false value. If both values are the same." What it's NOT is true.) What we're saying here is. $false_value = 0. They are known as True or False values. in programming. If they are both different. For example. before running the script. if ($contestant_one XOR $contestant_two) { print("Both can't win!").

and you often see this type of coding: $true_value = true. but the false_value won't print anything! Now replace true with 1 and false with 0. } else { print("that's not true"). ?> What you should find is that the true_value will print "1".Home and Learn You can replace the 1 and 0 with the words "true" and "false" (without the quotes). $false_value). in the script above. if you do. } The NOT operand is also used a lot with this kind of if statement: $true_value = true. But a note of caution. and see what happens: <?php $true_value = true. This is the same as: if ($true_value == 1) { print("that's true"). if (!$true_value) { 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". Try this script out. print ("true_value = " . and see what prints out. if ($true_value) { print("that's true"). $true_value). Boolean values are very common in programming. } –52– . $false_value = false. print (" false_value = " .

We won't be using these operators much. } So this asks. during your programming life. In the next section. we'll take a brief look at HTML forms.Beginners PHP You'll probably meet Boolean values a lot. you might have to consult the following: */% +-. "Do the variables match exactly?" Since one is text and the other is a number. An example would be: $number = 3. In which case. and how to get data from them. } else { print("Not the same"). This can make a difference. Don't worry about these too much. This is just an introduction. as we saw during the mathematical operators. so that we can do other things besides printing to the screen. the answer is "no". and the order of precedence. if ($number === $text) { print("Same"). or false. two new operators have been introduced: the triple equals sign ( = = =) and an exclamation. < <= > >= = = = != = && || And XOR OR Highest Precedence Lowest Precedence Ok. let's move on to some practical work. It's worth getting the hang of them! = = = and != = In recent editions of PHP. These are used to test if one value has the same as another AND are of the same type. if at all! Operator Precedence – a List Here's a list of the operators you've met so far. double equals ( != =). unless you're convinced that your math or logical is correct. $text = 'three'. –53– . if all of that has given you a headache.

you'll then see how to test the values you get back. and is called basicForm. drop down lists. then you know that the FORM tags can be used to interact with your users. so that you can get more practice with it. create the form above. Some familiarity with the above is assumed. ACTION and SUBMIT attributes in the form above.php. The HTML Form If you know a little HTML. because they are important. and submit buttons. if you like. here. It's in the scripts folder. you'll see how to get data from a basic HTML form. (This name will be VERY important!) Make sure the form loads ok in your browser.php. Use it as a template. Once you can get values from a form. check boxes. We'll use Conditional Logic a lot. You should be able to see a text box and a Submit button.Home and Learn HTML FORMS In this section. text areas. The above form can be found in the files you download. Here's what it should look like: –54– . So. as this is a book on PHP. Save your work as basicForm. But we'll discuss the METHOD. radio buttons. Things that can be added to a form are the likes of text boxes. A basic HTML form with a textbox and a Submit button looks like this: <html> <head> <title>A BASIC HTML FORM</title> </head> <body> <FORM NAME ="form1" METHOD =" " ACTION = ""> <INPUT TYPE = "TEXT" VALUE ="username"> <INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login"> </FORM> </body> </html> We won't explain what all the HTML elements do.

Method If you look at the first line of our form you'll notice a METHOD attribute: <FORM NAME ="form1" METHOD =" " ACTION = ""> The Method attribute is used to tell the browser how the form information should be sent.Beginners PHP Once you get that basic HTML form up and running. you need to know about the HTML attributes METHOD. save your work again and then click the Submit button on your form. then you'll need to get the details from textboxes. But our METHOD is blank. you then test it against a list of your users (this list is usually stored on a database. FORM Attributes If a user comes to your site and has to login. So change it to this: <FORM NAME ="form1" METHOD ="GET" ACTION = ""> To see what effect using GET has. Once you get the text that the user entered. First. we'll see how to get the value from the text box using PHP. The two most popular methods you can use are GET and POST. You should see this: –55– . ACTION and SUBMIT. which we'll see how to code for in a later section).

in other words. we have the following: ?Submit1=Login This is a consequence of using the GET method. but you'll see both techniques in action. So change you FORM line to this: –56– . Action The Action attribute is crucial. If you miss it out. or any other form of script. Using POST means that the form data won't get appended to the address in the address bar for all to see. Post The alternative is to use POST. a CGI script. Load your basicForm. and open it back up. We'll use POST. Change the first line of your FORM to this: <FORM NAME ="form1" METHOD ="POST" ACTION = ""> Close your browser down. In PHP. You use the GET method when the data you want returned is not crucial information that needs protecting. your form won't get sent anywhere.php page again. Your address bar will then look like this: The ?Submit1=Login part is now gone! That is because we used POST as the method.php. the same PHP script. a popular technique is to send the script to the same page that the form is on – send it to itself. After basicForm.Home and Learn The thing to notice here is the address bar. followed by form data. You can send the form data to another PHP script. It means. The data from the form ends up in the address bar. and then click the button. You'll see a question mark. We'll use that technique first. "Where do you want the form sent?". an email address.

Here's ours: <INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login"> You don't need to do anything special with a Submit button – all the submitting is done behind your back. then your data will get sent somewhere. save your work again and then click your submit button. But for now. Our Submit button is called "Submit1". This is important when the PHP script is on the same page as the HTML form. so change your HTML to this: <INPUT TYPE = "Text" VALUE ="username" NAME = "username"> The NAME of our textbox is "username". We'll put some PHP on the page to handle the form data. we can move on to processing the data that the user entered. Using PHP to get values from a HTML form Now that you know about METHOD. You can use this Name to test if the form was really submitted. To return data from a HTML form element.php"> So we're going to be sending the form data to exactly the same page as the one we have loaded – to itself. and SUBMIT. You then tell PHP the NAME of the textbox you want to work with. As long as SUBMIT has an ACTION set. Our textbox hasn't got a NAME yet. You won't see anything different. how to get values from our text box. But the NAME attribute of the Submit buttons comes in very handy. or if the user just clicked the refresh button. Getting values from a Text Box To get the text that a user entered into a textbox. ACTION. –57– . the textbox needs a NAME attribute. but you can call it almost anything you like. It's this name that we will be using in a PHP script. you use the following strange syntax: $_POST['formElement_name'].Beginners PHP <Form Name ="form1" Method ="POST" ACTION = "basicForm. First. but you shouldn't see any error message either! Submit The HTML Submit button is used to submit form data to the script mentioned in the ACTION attribute.

The text box itself. add the following PHP script to the code you have so far. print ($username). then you'd used this instead: $username = $_GET['username'].Home and Learn You can assign this to a variable: $Your_Variable = $_POST['formElement_name']. and click the button again. will still have "username" in it. So how does it work? The $_POST[] is an inbuilt function you can use to get POST data from a form. ?> </head> Save your work again. however. –58– . Your new text should appear above the textbox. and click the submit button to run your script. Click the button anyway. If you had METHOD = "GET" on your form.) You should see this appear above your text box: Delete the text "username" from the textbox. Make sure to add it the HEAD section of your HTML: <html> <head> <title>A BASIC HTML FORM</title> <?PHP $username = $_POST['username']. The Value attribute of the text box is what is being displayed. (Don't worry if you see an error message about "Undefined index". This is because the text box is getting reset when the data is returned to the browser. Before we explain all the syntax.

all we're doing is returning what the user entered and printing it to the page. At the moment. } We're now checking to see if the user entered the text "letmein". This is the problem you face when a PHP script is on the same page as the HTML. Checking if the Submit was clicked The reason why the text displays when the page is first loaded is because the script executes whether the button is clicked or not. and is being submitted to itself in the ACTION attribute. You can then assign this to a variable: $username = $_POST['username']. If so. you need the semi-colon to complete the line. When you first load the page. Whatever the VALUE was for your HTML element is what gets returned. Next comes the METHOD you want to use. So PHP will look for a HTML form element with the NAME username. $_POST['username']. } else { print ("You're not a member of this site"). POST or GET. You need to type a pair of square brackets next. print another message. you type the NAME of your HTML form element – username. change your PHP to this: $username = $_POST['username']. But we can use a bit of Conditional Logic to test what is inside of the variable. It then looks at the VALUE attribute for this form element. you might see the text "You're not a member of this site" displayed above the textbox.Beginners PHP So you begin with a dollar sign ($) and an underscore character ( _ ). in our case. friend!"). if ($username == "letmein") { print ("Welcome back. before you even click the button. In between the square brackets. the username is correct. It returns this value for you to use and manipulate. Of course. –59– . As an example. Try it out an see what happens. if not.

php –60– . If the user did click the Submit button. } else { print ("You're not a member of this site"). To see how it works. friend!"). then PHP will automatically return a value.Home and Learn To get round this. Make a note of where all those messy round. You can send it to an entirely different PHP page. To check if a submit button was clicked. if ($username == "letmein") { print ("Welcome back. Miss one out and you'll get an error! Setting the ACTION attribute to a different PHP page As was mentioned earlier. try this: €‰Chop out your PHP script from the basicForm. we have isset( ). you type what you want isset( ) to check. you don't have to submit your form data to the same PHP page.php page €ŠOpen up a new text file and paste it into there €‹Save your work with the name submitForm. you can do a simple check using another IF Statement. In between the round brackets. For us. Change you script to the following and try it out: if (isset($_POST['Submit'])) { $username = $_POST['username']. If it was. } } The new addition is in bold. then run your code. This just checks if a variable has been set or not. use this: if (isset($_POST['Submit'])) { } Now that looks a bit messy! But it actually consists of three parts: if ( ) { } isset( ) $_POST['Submit'] You know about the if statement. What you do is to check if the Submit button was clicked. square and curly brackets are. then no value will be set for the Submit button. this is $_POST['Submit']. But in between the round brackets. If the user just refreshed the page.

if ($username == "letmein") { print ("Welcome back.basicForm.php <html> <head> <title>A BASIC HTML FORM</title> </head> <body> <Form name ="form1" Method ="POST" Action ="submitForm.php. But you should now have two files: HTML ONLY . When the Submit button is clicked. from basicForm.php"> <INPUT TYPE = "TEXT" VALUE ="username" Name ="username"> <INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login"> </FORM> </body> </html> PHP ONLY . friend!"). } ?> –61– .php <?PHP $username = $_POST['username'].submitForm. the form data will be posted to this new PHP script.php"> To this <Form name="form1" Method ="POST" ACTION ="submitForm. } else { print ("You're not a member of this site").php"> The only thing you're changing is the script name.Beginners PHP €ŒChange the HTML from this: <Form name="form1" Method ="POST" ACTION ="basicForm.php to submitForm.

And we've left out the code that checks if the Submit button was clicked. But there is a problem with it . You're left with the VALUE that was set in the HTML. friend!"). For us. put your two files back together again. That means your form will disappear! We'll keep the PHP and HTML together. Keeping the data the user entered When our form is submitted. The code only gets executed IF the Submit is clicked. That means the PHP should be in the HEAD section of the HTML. as it was before we asked you to chop it out! In case you've forgotten. since we'll only be using one. That's because there's no PHP left in the first page. username kept appearing in the text box when the button was clicked. Posting form data to a different PHP script is a way to keep the HTML and PHP separate. which you will have noticed: the script gets executed on a new page. if ($username == "letmein") { print ("Welcome back. First. } } ?> </head> <body> <Form name ="form1" Method ="POST" Action ="basicForm. notice how there's no HTML tags.Home and Learn In the PHP script.php"> <Input Type = "text" Value ="username" Name ="username"> <Input Type = "Submit" Name = "Submit1" Value = "Login"> </FORM> </body> </html> –62– . } else { print ("You're not a member of this site"). the entire script we had was this: <html> <head> <title>A BASIC HTML FORM</title> <?PHP if (isset($_POST['Submit1'])) { $username = $_POST['username']. the details that the user entered get erased. You can keep the data the user entered quite easily. But there will be times when you do want to send form data to a different PHP page.

?>" In other words. To post the details back to the form. if ($username == "letmein") { print ("Welcome back. because it's all on one line. if you're asking the user to try again. –63– . Worse. } The new addition is in bold. } } else { $username ="". when the page is refreshed. You also need to amend your PHP code in the HEAD section to include an else statement: if (isset($_POST['Submit1'])) { $username = $_POST['username']. the VALUE attribute is now a PHP line of code. you'll see that it's set to "username". Better is to POST back the values that the user entered. This can be very annoying. Because the form gets posted back to itself. The line of code is just this: <?PHP print $username .e. you can use this: value="<?PHP print $username . But in the else statement. and thus keep the data the user has already typed out. } else { print ("You're not a member of this site"). ?> It's a bit hard to read.Beginners PHP If you look at the VALUE attribute of the text box in the HTML above. friend!"). i. we're just setting the value of the variable called $username for when the button is NOT clicked. this value will keep re-appearing in the textbox when the page is submitted. if you've left the Value attributes empty then everything the user entered will disappear.

Radio Buttons A Radio Button is a way to restrict users to having only one choice. Yes/No. there are some security issues associated with textboxes (and other form elements). here's a few exercise Exercise Add two text boxes and a Submit button to a HTML form. or answers to surveys and quizzes. Exercise Suppose your web site has only 5 users. How to handle other Form Elements with PHP We'll now take a look at some of the other elements you can have on a HTML form. Examples are : Male/Female. Now that you know a few things about getting values from HTML forms. ?>"> In other words. we're now printing out the VALUE attribute with PHP code.Home and Learn However. Here's a simple from with just two radio buttons and a Submit button: –64– . Display a suitable message. When the button is clicked. Invite the user to enter a first name and surname. instead of printing them out. But our new line of HTML for our textbox reads like this: <INPUT TYPE = 'TEXT' Name ='username' VALUE="<?PHP print $username . print out the person's full name. Don't worry about what is in the text boxes after the button is clicked. Create a HTML form to check if a visitor is one of the 5 users. display the first name and surname in the the textboxes. and how to return data from these. Exercise Using the same form as the previous exercise. So we'll see a more secure way to handle these later in the book.

The first Radio Button has a value of "male" and the second Radio Button has a value of female. again you access the NAME attribute of the HTML form elements. The file is called radioButton. if you don't fancy typing it all out yourself.Beginners PHP The HTML code for the above page is as follows: (You can find the code in the files you downloaded at the start of the book. Here's some PHP code. ?> –65– . in the scripts folder. In the HTML above. the NAME of the Radio buttons is the same – "gender".php) Open it up in your text editor. print $selected_radio. Add it to the HEAD section of your HTML: <?PHP $selected_radio = $_POST['gender']. <html> <head> <title>Radio Buttons</title> </head> <body> <Form name ="form1" Method ="Post" ACTION ="radioButton. it's these values that are returned. To get the value of a radio button with PHP code. as that's where we're posting the Form – to itself.php.php"> <Input type = 'Radio' Name ='gender' value= 'male'>Male <Input type = 'Radio' Name ='gender' value= 'female'>Female <P> <Input type = "Submit" Name = "Submit1" Value = "Select a Radio Button"> </FORM> </body> </html> Make sure you save your work as radioButton. When you're writing your PHP code.

Here's one way to do it: The PHP code: <?PHP $male_status = 'unchecked'. print $selected_radio.Home and Learn 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".checked or unchecked. if ($selected_radio == 'male') { $male_status = 'checked'. Select a radio button and click Submit button. The choice you made is printed to the page . though. is a little more complex than for text boxes Radio buttons have another attribute . Again. if (isset($_POST['Submit1'])) { $selected_radio = $_POST['gender']. The solution for radio Buttons. this is the same code you saw earlier – just access the form element called 'Submit1' and see if it is set. PHP is not retaining the value you selected. What you will notice. } else if ($selected_radio == 'female') { $female_status = 'checked'. You need to set which button was selected by the user. so you have to write PHP code inside the HTML with these values . The last line just prints the value to the page. Try out the code. though. however. we can add code to detect if the user clicked the Submit button: if (isset($_POST['Submit1'])) { $selected_radio = $_POST['gender']. The code only executes if it is. } Again.checked or unchecked. Again.either "male" or "female". when you try out the code is that the dot disappears from your selected radio button after the Submit is clicked. } } ?> –66– . $female_status = 'unchecked'.

We then need some conditional logic. We need to set a variable to "checked". Let's break that down. What is inside of the variable will be either the word "checked" or the word "unchecked". rather than the Submit button being clicked. ?> This is just a print statement. That's just in case the page is refreshed. ?> >Female <P> <Input type = "Submit" Name = "Submit1" VALUE = "Select a Radio Button"> </FORM> Did we say a little more complex? OK.php"> <Input type = 'Radio' Name ='gender' value= 'male' <?PHP print $male_status. Which it is depends on the logic from our long PHP at the top of the page. it's much more complex than any code you've written so far! Have a look at the PHP code inside the HTML first: <?PHP print $female_status. These both get set to unchecked. so we have an if. $female_status = 'unchecked'. As is the next line that puts which radio button was selected into the variable: $selected_radio = $_POST['gender']. First we have two variables at the top of the code: $male_status = 'unchecked'.Beginners PHP The HTML FORM code: <FORM name ="form1" method ="post" action ="radioButton. Next we have our check to see if Submit is clicked: if (isset($_POST['Submit1'])) { } Exactly the same as before. What is printed out is the value inside of the variable. ?> >Male <Input type = 'Radio' Name ='gender' value= 'female' <?PHP print $female_status. else … if construction: –67– .

So the code works because of the values inside of two variables: $male_status and $female_status. If the 'female' option button was clicked then set the $female_status variable to a value of 'checked'. Yes. Whereas Radio Buttons restrict users to only one choice. } else if ($selected_radio == 'female') { $female_status = 'checked'. Here's a page that asks users to choose which course books they want to order: –68– . do another. if it's 'female'.Home and Learn if ($selected_radio == 'male') { } else if ($selected_radio == 'female') { } All we're doing is testing what is inside of the variable called $selected_radio. But look at what we're doing: if ($selected_radio == 'male') { $male_status = 'checked'. } If the 'male' button was clicked then set the $male_status variable to a value of 'checked'. the code is very messy – but radio Buttons can be a tad tricky. when you want to retain the value of the selected item. checkboxes are used to give visitors a choice of options. you can select more than one option with Checkboxes. Speaking of tricky – checkboxes are up next! Checkboxes Like Radio buttons. If it's 'male' do one thing.

five items can be selected. You don't want the ticks disappearing from the checkboxes. $ch4 = 'unchecked'. and have PHP "remember" which items were chosen. Only three are chosen at the moment. just in case of errors.Beginners PHP As you can see.php. The script you're looking for is checkboxes. $ch5 = 'unchecked'. we've included it in the files you downloaded at the start of the book. and is in the scripts folder. $ch3 = 'unchecked'. When the button is clicked you. if the user has failed to enter some other details incorrectly. as the programmer. $ch2 = 'unchecked'. Here it is in full: <html> <head> <title>Checkboxes</title> <?PHP $ch1 = 'unchecked'. –69– . Because the code is a little more complex. The same is true for checkboxes. want to do at least two things: record which checkboxes were ticked. Let's have a look at one solution to the problem. We saw with Radio Buttons that this can involve some tricky coding. Open it up and take a look at the code.

if ($ch5 == 'php') { $ch5 = 'checked'. } } if (isset($_POST['ch4'])) { $ch4 = $_POST['ch4']. } } if (isset($_POST['ch2'])) { $ch2 = $_POST['ch2']. } } if (isset($_POST['ch3'])) { $ch3 = $_POST['ch3']. } } if (isset($_POST['ch5'])) { $ch5 = $_POST['ch5']. } } } ?> –70– . if ($ch2 == 'word') { $ch2 = 'checked'. if ($ch4 == 'web') { $ch4 = 'checked'.Home and Learn if (isset($_POST['Submit1'])) { if (isset($_POST['ch1'])) { $ch1 = $_POST['ch1']. if ($ch3 == 'excel') { $ch3 = 'checked'. if ($ch1 == 'net') { $ch1 = 'checked'.

php"> <Input type = 'Checkbox' Name ='ch1' value ="net" <?PHP print $ch1. ?> >PHP for the Beginner <P> <INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Choose your books"> </FORM> </body> </html> Note one thing about the HTML checkbox elements: they all have different NAME values (ch1. and treat them as separate entities (but some advocate treating them just like Radio Buttons). etc). ?> >Microsoft Excel <P> <Input type = 'Checkbox' Name ='ch4' value="web" <?PHP print $ch4. the technique is to check whether each checkbox element has been checked or not. First we set up five variable and set them all the unchecked. we gave the buttons the same NAME. Because the user can select more than one option with Checkboxes. ?> >Web Design <P> <Input type = 'Checkbox' Name ='ch5' value="php" <?PHP print $ch5.NET <P> <Input type = 'Checkbox' Name ='ch2' value="word" <?PHP print $ch2. ch2 ch3.Beginners PHP </head> <body> <FORM NAME ="form1" METHOD ="POST" ACTION ="checkBoxes. ?> >Visual Basic . it makes sense to give them different NAME values. That's because only one option can be selected with Radio Buttons. just like we did before: –71– . In your PHP code. When we coded for the Radio Buttons. ?> >Microsoft Word <P> <Input type = 'Checkbox' Name ='ch3' value="excel" <?PHP print $ch3. It's more or less the same as for the radio Buttons.

This one says. The rest of the if statements are the same – one for each checkbox on the form. we have another "isset( )" function: if (isset($_POST['ch1'])) { } This time. $ch2 = 'unchecked'. ?> >Visual Basic . they have no value at all. $ch4 = 'unchecked'. The last thing we need to do is to print the value of the variable to the HTML form: <Input type = 'Checkbox' Name ='ch1' value ="net" <?PHP print $ch1. If the isset( ) function is true. we're checking to see if a checkbox was set. The code we need to execute is to put the text 'checked' inside of the variable called $ch1. If the checkbox is ticked.Home and Learn $ch1 = 'unchecked'. though. And so the isset( ) function will be true. The next thing is the same as well: check to see if the Submit button was clicked: if (isset($_POST['Submit1'])) { } Inside of this code. If they are not ticked.NET –72– . then you'll have to deal with a lot of "Undefined" errors. however. $ch5 = 'unchecked'. We need to do this because of a peculiarity of HTML checkboxes. We need to know what is inside of it. it will return a value. } This is yet another If Statement! But we're just checking the value of a variable. then our code inside of the if statement gets executed: if ($ch1 = = 'net') { $ch1 = 'checked'. "If the value inside of the variable called $ch1 is 'net' then execute some code. $ch3 = 'unchecked'. so nothing is returned! If you try the code without checking if the checkboxes are set.

we'll leave the subject. and move on. though. is that to get the job done we used Conditional Logic. This will either be "unchecked" or "checked". ?> So we're just printing what is inside of the variable called $ch1. but none seem simple! The point here. as we're tackling loops! –73– . There are other solution for checkboxes. For now. this is the same code you saw with the Radio Buttons. though. It's a bit of a bumpy ride in the next part. You'll learn more about dealing with HTML forms in a later sections. The PHP part is: <?PHP print $ch1.Beginners PHP Again.

it’s exactly the same. and what to do after it’s finished one lap (known as the update expression). you think. But it’s an awful lot easier with them. Except a programming loop will go round and round until you tell it to stop. either. print $counter . And not much code. } ?> –74– . If I told you to move a finger around in a loop. You use them when you want to execute the same code over and over again. You can programme without using loops. For Loops Here’s a PHP For Loop in a little script.Home and Learn Loops So what’s a loop then? A loop is something that goes round and round. you’d have no problem with the order (unless you have no fingers!) In programming. 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. You want to add up the numbers 1 to 4: 1 + 2 + 3 + 4.where to start your loop. $start++) { $counter = $counter + 1. <?PHP $counter = 0. we'll discuss those first. $start = 1. for($start. We'll discuss a few flavours of programming loops. "<BR>". but as the For Loop is the most used type of loop. $start < 11. You could do it like this $answer = 1 + 2 + 3 + 4 print $answer Fairly simple. Run your code and test it out. Consider this. A loop would make life a lot simpler. You also need to tell the programme two other things . Type it into new PHP script and save your work.

start++) { The result is the same – the start number for this loop is 1 End Value Next. The format for a For Loop is this: for (start value. In other words. a Boolean value. 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. This can be a number. in this case for. $start < 11. PHP will bail out of the loop. $start++) { Or you can assign your loop value right in the For Loop code: for($start = 1. A popular name for the initial variable is the letter i .Beginners PHP How did you get on? You should have seen the numbers 1 to 10 printed on your browser page. Here. Like all variables. If we didn’t –75– . etc. Update Expression Loops need a way of getting the next number in a series. for($start. start < 11. $start++) { When the value of $start is 11 or higher. update expression) { } The first thing you need to do is type the name of the loop you’re using. we’re telling PHP to keep going round the loop while the value of the variable $start is Less Than 11. you can make up your own name. like we did: $start = 1 for($start. it would be stuck on the starting value. start the loop at what number? We used this: $start = 1 We’re assigning a value of 1 to a variable called $start. you have to tell PHP when to end your loop. If the loop couldn’t update the starting value. a string. You can set the initial condition before the loop begins. $start < 11. end value.

So our whole loop reads “Starting at a value of 1.(the double minus sign). A Times Table Programme There's a script called timesTable. Then inside the loop.).Home and Learn update our start value. 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 (--). use $counter. Increase the starting value by one each time round the loop. In other words. but we won’t go into that.. we'll write a little Times Table programme. you need to tell the loop how it is to go round and round. Can you guess what will happen? Will it crash. "<BR>". our loop would get stuck on 1. exactly the same as what we’re doing with the start variable.” Every time the loop goes round. So we could have put this instead: $counter ++ The effect would be the same. keep going round and round while the start value is less than 11.php amongst the files you downloaded (in the scripts folder. or not? Or will it print something out? Better save your work. We used this: $start++ In a lot of programming language (and PHP) the double plus symbol (++) means increment (increase the value by one). try setting the value of $counter to 11 outside the loop (it’s currently $counter = 0). it looks like this: –76– . Notice that we’re just incrementing the counter variable by 1 each time round the loop. When loaded into the browser. print $counter . just in case! To get more practice with the For Loop. As an experiment. the code between our two curly brackets { } gets executed: $counter = $counter + 1.

and the end of the loop will come from the End Number textbox. when the button is clicked we'll print the Times Table to the page. When the button is clicked. You can have a different Times Table. Code for the PHP Times Table The code for the Times Table uses a For Loop. The Start for the loop will come from the Start Number textbox. Here's the code in full: –77– . the output will be something like this: In other words.Beginners PHP What we're going to do is to get the values from the textboxes and create a Times Table proramme. depending on what values you enter in the textboxes.

print $start . $times = $_POST['txtTimes']. for($start. This is so that the "Multiply By" textbox will have a default value when the page is loaded. " = " . } The first line just puts a value in the variable called $times . $times . Next we use the isset( ) function again. $times = $_POST['txtTimes']. we use the following: $start = $_POST['txtStart']. } } ?> Code Explanation We need all those numbers from the textboxes on the form. This is exactly the same as you saw in the last section. $times = $_POST['txtTimes']. $end = $_POST['txtEnd']. To get the values from the textboxes. " multiplied by " . so we start with: $times = 2.Home and Learn <?PHP $times = 2. –78– . $start <= $end. $start++) { $answer = $start * $times. $end = $_POST['txtEnd']. just to check if the user clicked the Submit button. $answer . if (isset($_POST['Submit1'])) { $start = $_POST['txtStart']. if (isset($_POST['Submit1'])) { $start = $_POST['txtStart']. $end = $_POST['txtEnd']. "<BR>".

and an update expression. Look at the end value. The code inside the for loop. however. then 3. So it's really doing this: $answer = 1 * 2. is this: $answer = $start * $times. an end value. the variable $times holds the times table. The answer is then stored in the variable that we called $answer. The last part of the loop code is the update expression. This works because we're increasing the value of $start each time round the loop. $start <= $end. This is being multiplied by whatever is inside the variable $start. $start <= $end. This will be whatever number the user entered in the first textbox. $start++) { $answer = $start * $times. we've typed the NAME of the HTML textboxes. So this gives us the values that the user entered on the form. an end value. And that's the essence of for loops: provide a start value. You just assign the values from the textboxes to the new variables using $_POST[]. the 2 times table by default. the code that gets executed each time round the loop. Remember. The starting value is coming from the variable called $start. Next comes out For Loop: for($start. this is code you met in the last section. etc. In between the square brackets. } Let's look at that first line again: for($start. though: $start <= $end 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.Beginners PHP Again. –79– . and how you want to update each time round the loop. then 2. 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". $start++) { So we have a starting value for our loop. Each time round the loop. The default is 1. $start will have a different value – first 1. The variable called $end is a fixed value. and comes from the textbox on the form.

$counter . $answer . $answer = 3 * 2. If counter is less than eleven then the condition is true. The structure of a while loop is more simple than a for loop. A while loop will stop going round and round when a condition is false. you have the option to use a while loop. The loop goes round and round while the condition is true. while ($counter < 11) { print (" counter = " . All it does is increment a variable called counter: $counter = 1. When the condition is false. Why doesn't it print anything out? Anything you can do to trap this error? Another if statement somewhere. } The condition to test for is $counter < 11. Here’s the syntax for a while loop: while (condition) { statement } And here’s some code to try. " multiplied by " . Children are like that. " = " . –80– . Especially if they enter a 10 as the start number and a 1 as the end number. This is just concatenation. which I’m sure the children will discover. Each time round the while loop. because you’re only evaluating the one condition. $times . we displayed the result to the page like this: print $start . that condition is checked.Home and Learn $answer = 2 * 2. "<BR>". If you have children. See if you can work out what all the parts do! And that’s it – your very own times table generator. $counter++. your programme is not perfect. Of course. perhaps? While Loops Instead of using a for loop. They’ll be very impressed and tell you how brilliant you are. the programme breaks out of the while loop. When $counter is greater than eleven then the condition is false. etc Finally. show them the programme you wrote. "<BR>").

$answer . " times " . Like this: $counter = 1. This line will now be ignored. $start = 1. } The while loop calculates the 2 times tables. $counter . } Notice the two forward slashes before $counter++. "<BR>"). Can you see what’s going on? Make sure you understand the code. while ($counter < 11) { print (" counter = " . $times = 2. You’d create one of these if you didn’t provide a way for you condition to be evaluated as true. " = " . "<BR>"). it’s a good idea to go back and read this section again. up to a ten times 2. Here’s a while loop that prints out the 2 times table. print ($start . $start++. while ($start < 11) { $answer = $start * $times. You won’t be considered a failure. Because the loop is going round and round while counter is less than 11. We can create an infinite loop with the while loop above. be careful that you don’t create an infinite loop. $times . the loop will never end – $counter will always be 1. Honest! Do While loops This type is loop is almost identical to the while loop. //$counter++. $answer = 0.Beginners PHP If you use a while loop. except that the condition comes at the end: do statement while (condition) –81– . All we have to do is comment out the line where the $counter variable is incremented. If not.

while ($counter < 11) { print(" counter = " + $counter + "<BR>"). For now. and how useful they can be. we'll take a look at what arrays are. you can use the break statement. this involves nothing more than typing the word break. (Yes. The break statement There are times when you need to break out of a loop before the whole thing gets executed. $counter++. which you'll study next.Home and Learn The difference is that your statement gets executed at least once. It's quite useful for things called arrays. Fortunately. Here’s some not very useful code that demonstrates the use of the break statement: $TeacherInterrupts = true. In the next section. } Try the code out and see what happens. For Each This type a loop is a special loop. Don’t worry too much about do … while loops. $counter = 1. Or. if ($TeacherInterrupts == true) break. the condition could be met before your statement gets executed. In which case. You'll see this type of loop soon! Ok. that's enough of loops. In a normal while loop. you want to break out of the loop because of an error your user made. there'll be loops!) –82– .

The problem is. Bu t like loops. you type this: –83– . $Order_Number3. and you need to do something with them. An array is like a special variable. But an array is! An array can hold all your orders under a single name. and how to set up your own arrays What is an Array? You know what a variable is – just a storage area where you hold numbers and text. in the array above) and. you can just use a single name. You set up an array like this: $Order_Number = array(). $Order_Number2. you'll see just what they are. If you have a list of items (like a list of customer orders. And you can access the orders by just referring to the array name. a variable will hold only one value. then it would be quite cumbersome to do this: $Order_Number1 = "Black shoes". when you're first starting out. With an array. or more than one string. 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. which can hold more than one number. $Order_Number3 = "Red shoes". In this section.Beginners PHP Arrays Arrays are another of those things that help enormously when you're programming. we had four items. If that's a bit confusing right now. after an equals sign. and $Order_Number4. let’s make a start on explaining how arrays work. Setting up an Array In the code above. You can store a single number in a variable. and all with a different variable name: $Order_Number1. they can be quite difficult to master. $Order_Number2 = "Tan shoes". First you type out what you want your array to be called ($Order_Number. $Order_Number4 = "Blue shoes". for example). or a single string. at a time.

followed by the equals sign and a right angle bracket ( => ). and some data for that position. "Winter" is in position 1. So the name of the array is $seasons. Method One – Type between the round brackets The first method involves typing your values between the round brackets of array(). we're setting up an array to hold the seasons of the year: $seasons = array("Autumn". and give it the name $Order_Number. 3 => "Spring". "Spring" is in position 2. Each value is separated by a comma: ("Autumn". 2=> "Winter". All we're doing with our line of code is telling PHP to set up an array. Between the round brackets of array(). "Summer"). 2 => "Winter". you do it like this: $seasons = array(1 => "Autumn". "Winter". Careful of all the commas. and "Summer" is in position 3. 4=> "Summer" –84– . "Summer") Arrays work by having a position. So you type a number for your key. In the code below. "Spring". "Winter".Home and Learn array(). The first position is always zero. If so. Here's the keys and values that are set up in the array above: 1=> "Autumn". But the position is know as a Key. The item stored under key 1 is "Autumn". The Key then has a value attached to it. But there's nothing in the array yet. 3=> "Spring". the first Key is now 1 and not 0. You can use two basic methods to put something into an array. we have typed some values. So setting up an array just involves typing the word array followed by a pair of round brackets. "Spring". This is enough to tell PHP that you want to set up the array. "Autumn" is in position zero. In the array above. when you set up an array like this. In the above array. 4 => "Summer"). and the item stored under key 4 is "Summer". You can specify your own numbers for the Keys. unless you tell PHP otherwise. The last key is 4. Miss one out and you'll get error messages.

$Array_Name = array(10. only this time we're specifying our own key: $Array_Name = array(1 => 10. 4=> 40 So the key name is typed before the => symbol. 2 => "Spring". 3=> 40 Here's the same array again. Because no keys were specified. it would be this: 0=> "Autumn". 4=> "Summer" –85– . 2 => 20. 2=> 30. 20. 4 => 40).Beginners PHP If you let PHP set the keys for you. 3=> "Summer" You can have numbers for the values of your keys. 30. 40). Here's an array that stores the numbers 10. 2=> "Spring". PHP will set your array up like this: 0=> 10. 3=> 30. 3=> 30. and the data stored under this key is to the right. You can store text and numbers in the same array: $Array_Name = array(1 => 10. 2=> "Spring". This array will then look like this: 1=> 10. 30 and 40. 1=> 20. 20. 1=> "Winter". 3 => 30. 2=> 20. 4 => "Summer"). 3 => 30. The above array would then look like this: 1=> 10.

$times = 2. PHP will then see your array like this: 1=> "Autumn". 2=> "Winter".Home and Learn Method two – Assign values to an array Another way to put values into an array is like this: $seasons = array(). 4=> "Summer" This method of creating arrays can be very useful for assigning values to an array within a loop. $seasons[]="Summer". $seasons[]="Spring". followed by a pair of square brackets: $seasons[] After the equals sign. 3=> "Spring". $seasons[]="Winter". $seasons[]="Autumn". 2=> "Spring". 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. the array is first set up with $seasons = array(). If you want different numbers for your keys. 3=> "Summer" This is exactly the same as the array you saw earlier. Because no numbers were typed in between the square brackets. $seasons[2]="Winter". $seasons[4]="Summer". Here. then simply type them between the square brackets: $seasons[1]="Autumn". you type out what you want to store in this position. 1=> "Winter".. $seasons[3]="Spring". PHP will assign the number 0 as the first key: 0=> "Autumn". Here's some code: $start = 1. –86– .

"Spring". print $key_data. and the array key numbers. $start++) { $answer[$start] = $start * $times. you'll be creating them just like above! Getting at the values stored in your arrays OK. But the "Key" is the key. To get at what is inside of an array. You could do it like this: $seasons = array("Autumn". When you get some experience with arrays. print $seasons[1]. "Winter". "Spring". print $seasons[0]. for ($start. though. "Summer"). You just type the key number between the square brackets of your array name: print $Array_Name[0]. "Summer"). ?> The array is the same one we set up before. } Don't worry if you don't fully understand the code above.Beginners PHP $answer = array(). You can also assign this value to another variable: $key_data = $Array_Name[0]. so you now know how to store values in your array (with method one or method two). just type the key number you want to access. But how do you get at those values? Well. print $seasons[2]. Here's an example for you to try: <?php $seasons = array("Autumn". In the above code. we're printing out what is held in the 0 position (Key) in the array. print $seasons[0]. Suppose you wanted to print out all the values in your array. "Winter". The point is that the values in the array called $answer. It's a lot easier using a loop. print $seasons[3]. $start < 11. there are few ways you can do it. are being assigned inside the loop. –87– .

$full_name["Richard"] = "Wright". This can help you remember what's in a key. when you use numbers for the keys. Fans of a certain band will know exactly who these people are! But look at the keys and values now: David => "Gilmour".Home and Learn Or you could do it like this: for ($key_Number = 0. Richard => "Wright" This is easier to remember than this: 0 => "Gilmour". They can be text. –88– . When you use text for the keys. you're using a Scalar array. 3 => "Wright" To access the values in an Associative array. $key_Number++) { print $seasons[$key_Number]. $full_name["David"] = "Gilmour". 1 => "Mason". Nick => "Mason". 2 => "Waters". $full_name["Nick"] = "Mason". Roger => "Waters". or what it's supposed to do. $full_name["Roger"] = "Waters". you're using an Associative array. Here's an array that sets up first name and surname combinations: $full_name = array(). just refer to the Key name: print $full_name["David"].Using Text as Keys Your arrays keys don't have to be numbers. } If you have many array values to access. then using a loop like the one above will save you a lot of work! Array . $key_Number < 4.

storing the results in your variables. In the script above. foreach ($full_name as $key_name => $key_value) { print "Key = " . $full_name["Nick"] = "Mason". another technique is used to loop round them – the For Each loop. we set up the array as normal. } This type of loop is a little more complex than other loops you've met. PHP knows that it's accessing the key name first and then the key value. " Value = " .Beginners PHP Arrays and For Each However. "Get the Key and its Value from the array called $full_name. that was $full_name. It then returns the values into your variable names. –89– . It knows this because of the => symbol between the two. $full_name["Roger"] = "Waters". For us. whatever they may be. The Key is called $key_name in the script above. it then loops round and returns the next Key/Value pair. Inside of the round brackets. But the first line of the loop is this: foreach ($full_name as $key_name => $key_value) { Notice that the name of the loop is one word: foreach and NOT for each. Once your loop code is executed (a print statement for us). But these are just variable names. $full_name["Richard"] = "Wright". $key_value . You can call them almost anything you like. Next is this: as $key_name => $key_value This means. because Associative arrays don't have numbers for the keys. we have this: $full_name as $key_name => $key_value You start by typing the name of the array you want to loop round. $full_name["David"] = "Gilmour". Would could have had this: foreach ($full_name as $first_name => $surname) { When you use foreach. Next comes the round brackets. $key_name . and the value is called $key_value. Here's one in action: $full_name = array(). "<BR>".

you just use the assort() function. Like this: $numbers = array(). here's a few useful things you can do with arrays. This involves nothing more complex than typing the word asort. $full_name["Nick"] = "Mason". $numbers[]="10". If you want to sort using the Key. print $numbers[1]. $full_name["Roger"] = "Waters". type in the name of your Associative array: asort($full_name). print $numbers[3]. $numbers[]="8". The "a" also tells PHP to sort by the Value. suppose your array values are not in alphabetical order. and NOT by the key. followed by round brackets. $full_name["David"] = "Gilmour". (If you don't have the "a" before "sort". print $numbers[0] . Before we give you some examples to try out. print $numbers[2] .Home and Learn If you need to access values from an Associative array. sort($numbers). The letter "a" tells PHP that the array is an Associative one. the surnames will be sorted. then you can use ksort() instead. use a foreach loop. In our script above. Like this one: $full_name = array(). $numbers[]="6". To sort this array. –90– . $full_name["Richard"] = "Wright". your key names will turn in to numbers!). $numbers[]="2". In between the round brackets. For example. then. Sorting Array values There may be times when you want to sort the values inside of an array. If you have a Scalar array (numbers as Keys). then you leave the "a" off.

If you want to sort in reverse order then you need the following: rsort() – Sorts a Scalar array in reverse order arsort() . Refresh the page and you should see a different number between 1 and 6 display. "Winter". The count function The count( ) function is useful when you want to return how many elements are in your array. This could be useful in games of chance. Try the script out. You can then use this in a for loop. 5 => 5. 3 => 3. $key_Number < $array_count. Here's a simple script that simulates a single dice throw: <?PHP $numbers = array(1 => 1. "Summer"). 1). you need two things: the name of your array. print $random_key. In between the round brackets. You start off with the function array_rand( ). 2 => 2. ?> The function that returns the random key is this: array_rand($numbers. and how many random keys you want to grab. "Spring". 1). $key_Number++) { print $seasons[$key_Number]. we used this: –91– .Beginners PHP The numbers are then sorted from lowest to highest. $array_count = count($seasons). for ($key_Number = 0.Sorts the Values in an Associative array in reverse order krsort() . 6 => 6).Sorts the Keys in an Associative array in reverse order Random Keys from an Array You can grab a random key from an array. only this time with the count function: $seasons = array("Autumn". $random_key = array_rand($numbers. 4 => 4. Here's an example we used earlier. } To get how many elements are in the array.

To round off this chapter on arrays. " ". ?> Script Two . print $seasons[2] . print $seasons[1] . " ". here a few script for you to try out. The file you're looking for is called scripts. print $seasons[2] . " ". "Spring". " ". 2 => "Winter". " ". You can then use this value as the end condition in you loop: for ($key_Number = 0. print $seasons[3] . 3 => "Spring". if you want to copy and paste them. ?> –92– . 4 => "Summer"). In between the round brackets.Set up an array and print out the values <?PHP $seasons = array("Autumn". $key_Number < $array_count. " ".Set up an array with your own Keys <?PHP $seasons = array(1 => "Autumn". The scripts are amongst the files you downloaded at the start of the book (in the scripts folder). So you type the word count and then the round brackets. we're saying. print $seasons[3].Home and Learn $array_count = count($seasons). "Summer"). you type the name of your array. print $seasons[4]. "Winter". $key_Number++) Here. which we then assign to a variable called $array_count.txt. Script One . The function then counts how many elements are in the array. print $seasons[1] . print $seasons[0] . "keep looping round as long as the value in $key_Number is less than the value in $array_count.

$start++) { $answer[$start] = $start * $times. print $seasons[0] . print $seasons[1] . } –93– . print $seasons[1] . $seasons[]="Spring". print $seasons[2] . $seasons[]="Winter". 2 => "Spring". print $seasons[4].Looping round values in an array <?PHP $start = 1. " ". " ". $times = 2. $answer = array(). for ($start. 3 => 30. ?> Script four .Set up an array with mixed values <?PHP $seasons = array(1 => 10. $seasons[]="Autumn". 4 => "Summer"). " ". " ". $seasons[]="Summer". ?> Script Five .Assign values to an array: Method Two example <?PHP $seasons = array(). print $seasons[3] . " ". " ".Beginners PHP Script Three . print $seasons[3]. print $seasons[2] . $start < 11.

"Summer").Using text as Keys <?PHP $full_name = array(). $full_name["Roger"] = "Waters". print $full_name["David"]. "<BR>". $key_Number++) { print $seasons[$key_Number]. ?> Script Eight . ?> Script Six . "Winter".Home and Learn print $answer[1] . print $full_name["Nick"] .Looping round values in an array: example 2 <?PHP $seasons = array("Autumn". } ?> Script Seven . $full_name["David"] = "Gilmour". print $answer[10].Looping round an Associative array using For Each <?PHP $full_name = array(). $key_Number < 4. –94– . " ". " ". $full_name["Nick"] = "Mason". $full_name["Nick"] = "Mason". print $answer[4] . for ($key_Number = 0. $full_name["Richard"] = "Wright". $full_name["David"] = "Gilmour". "Spring". " ". print $answer[8] . $full_name["Roger"] = "Waters".

Beginners PHP

$full_name["Richard"] = "Wright"; foreach ($full_name as $first_name => $surname) { print "Key = " . $first_name . " Value = " . $surname . "<BR>"; } ?>

Script Nine - Sorting Arrays (Associative)
<?PHP $full_name = array(); $full_name["Roger"] = "Waters"; $full_name["Richard"] = "Wright"; $full_name["Nick"] = "Mason"; $full_name["David"] = "Gilmour"; foreach ($full_name as $first_name => $surname) { print "Key = " . $first_name . " Value = " . $surname . "<BR>"; } print "<P>"; ksort($full_name); foreach ($full_name as $first_name => $surname) { print "Key = " . $first_name . " Value = " . $surname . "<BR>"; } ?>

Script Ten - Sorting Arrays (Scalar)
<?PHP $numbers = array(); $numbers[]="2"; $numbers[]="8"; $numbers[]="10";

–95–

Home and Learn

$numbers[]="6"; print $numbers[0] . " "; print $numbers[1] . " "; print $numbers[2] . " "; print $numbers[3]; ?>

Arrays are an important programming technique, and they help your coding enormously, once you master them. In the next section, we'll take a look at another important area for you to work on string techniques.

–96–

Beginners PHP

String Manipulation

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.

Changing Case
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. <?PHP $full_name = 'bill gates'; if (isset($_POST['Submit1'])) { $full_name = $_POST['username']; $full_name = ucwords($full_name); } ?>

–97–

Home and Learn

The first line just makes sure that the lowercase version is placed into the textbox when the page loads: $full_name = 'bill gates'; 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: $full_name = ucwords($full_name); 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: $full_ sentence = ucfirst($full_ sentence); To convert all the letters to either upper or lowercase, use these: strtoupper( ) strtolower( ) Here's an example of how to use them: $change_to_lowercase = "CHANGE THIS"; $change_to_lowercase = strtolower($change_to_lowercase); $change_to_uppercase = "change this"; $change_to_uppercase = strtoupper($change_to_lowercase); Again, the variable or text you want to change goes between the round brackets of the function. This is then assigned to a variable.

Trimming White Space
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 PGP functions to help you do this:

–98–

Beginners PHP

Suppose your user has entered this in the textbox: " username " 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 $space = " username "; $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 $space = trim(" username "); $letCount = strlen($space); print $letCount; ?> When you run the script now, you should find that the variable has the correct number of characters - 8. 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.

Shuffle characters
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:

–99–

1.0. Internet Explorer returns something like this: Mozilla/4. start. MSIE 6. en-GB. U.4322.0. The syntax for the strpos ( ) function is: strpos(string_to_search. . $full_name = str_shuffle($full_name).1. . $full_name = "bill gates".7. $letter_position = strpos($full_name. If you try it with the Firefox browser. start) You need to supply at least the first two. you'd get something like this: Mozilla/5. but the function takes a variable or direct text and shuffles the characters around.NET CLR 1. 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.1. Here's a simple example.0 (Windows. –100– . you can use a string function to search for a short string inside of this very long one. print $letter_position. For example.Home and Learn <?PHP $full_name = 'anagram'. ?> Only three lines long. The third.5) Gecko/20041110 Firefox/1.NET CLR 2. SV1. print $full_name. Windows NT 5. print $agent. is optional. string_to_find. Windows NT 5. "b").50215) If you're testing which browser the user has. rv:1. you can get which browser the user has with this: $agent = $_SERVER["HTTP_USER_AGENT"].0 However. A PHP string function you can use is strpos( ).0 (compatible.

Boolean. But it can be a different kind of false! So use = = =. "B"). 'KONQUEROR')) { print "Konqueror". } else if (strpos(strtoupper($agent). What happens when you run the script? Nothing! At least. If a string is not found. –101– . $full_name = "bill gates". Like this. A value of false in PHP can be tested for by using the triple equals operator. etc. That's because PHP considers the first character of the string to be at position 0. "B"). the third at position 2. if ($letter_position === false) { print "Character not found " .Beginners PHP When you run the script. just in case the character you're searching for is at position 0. $letter_position = strpos($full_name. you need to use this operator. 'FIREFOX')) { print "Firefox". remember. To this: $letter_position = strpos($full_name. but what type of value it is: integer. 'MSIE')) { print "Internet Explorer". if ( strpos(strtoupper($agent). a value of 0 is returned. a value of 0 is returned. "b"). That's because if strpos can't find your characters. Try changing strpos() from this: $letter_position = strpos($full_name. you don't get a value back. and "bill gates" begins with this letter. PHP is a little bit quirky with zeros. the second character at position 1. } else { print "Character found". Here's a script that checks which of four browsers the user has: $agent = $_SERVER['HTTP_USER_AGENT']. it returns a value of false. } else if (strpos(strtoupper($agent). Since we were searching for the letter "b". string. It seems them as having a false value as well. } The triple equals operator ( = = =) not only checks for a value. etc.

Home and Learn

} else if (strpos(strtoupper($agent), "LYNX")) { print "Lynx"; } 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!

Splitting a line of text
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: Poll number 1, 1500, 250, 150, 100, 1000 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: $text_line = "Poll number 1, 1500, 250, 150, 100, 1000"; 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

–102–

Beginners PHP

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: explode(separator, string_to_split) 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: $text_line = "Poll number 1, 1500, 250, 150, 100, 1000"; $text_line = explode("," , $text_line); So we're saying, "Look for a comma in the text, and split the line of text into separate pieces." Once PHP does its job, it puts all the parts into the variable on the left hand side of the equals sign ( = ), which was $text_line for us. This variable will then be an array! To get at the pieces of the array, access it in the normal manner. Here's some code to try: <?PHP $text_line = "Poll number 1, 1500, 250, 150, 100, 1000"; $text_line = explode(",",$text_line); 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); Run your code and see what happens.

–103–

Home and Learn

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: $text_line = "Poll number 1, 1500, 250, 150, 100, 1000"; $text_line = explode(",",$text_line); for ($start=0; $start < count($text_line); $start++) { print $text_line[$start] . "<BR>"; } In the for loop above, we set a start value to zero. The end condition is this: $start < count($text_line) 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). Inside the loop, we have a normal print statement: print $text_line[$start] . "<BR>"; To get at each element in the array, this is used: $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.

Joining text into a single line
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( ): $seasons = array("Autumn", "Winter", "Spring", "Summer"); $new_textline = implode(",", $seasons) 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( ).

–104–

Beginners PHP

implode(separator, text_to_join) So implode( ) will join all the text together and separate each part with a comma, in the code above. Of course, you don't have to use a comma. You could use a dash: $new_textline = implode("-", $seasons) Or any other character: $new_textline = implode("#", $seasons) Even a space: $new_textline = implode(" ", $seasons) The implode( ) function can come in handy, if you need to work with single lines of text.

PHP and Escaping
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 $string = 'John's Car'; print $string; ?> 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: $string = "John's Car"; Or you could escape the apostrophe. You escape a character by typing a "slash" before it. Like this: $string = 'John\'s Car';

–105–

Home and Learn

If you try that out, you should find that the string prints correctly. Now try this script: <?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.

String function list
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: http://www.w3schools.com/php/func_string_chr.asp, http://www.zend.com/manual/ref.strings.php Here's our list, though. Click on a link to go to that string function.

–106–

$string2. If you want to disguise your email address.com". Can be used an alternative to the print statement. "me. print $email_address. print $ascii_num echo( ) Can be used as an alternative to the print statement. you can use it like this: $ascii_num = ord("@"). Tells you how similar two strings of text are. For example. The syntax is: similar_text($string1. Grab a number of character from a string. Replace one string with another. Gets the length of a string. the ASCII value 64 is the @ symbol on a UK keyboard. echo $display_data. Find out what the ASCII value of a character is. print $display_data. These do the same thing: $display_data = "something to display". $percent) –107– . ord( ) Find out what the ASCII value of a character is with this string function. similar_text( ) As it's name suggests. Repeats a character a specified number of times. chr( ) Converts an ASCII value to its equivalent character.Beginners PHP String Function chr( ) ord( ) echo( ) similar_text( ) str_repeat( ) str_replace( ) str_word_count( ) strlen( ) substr( ) Explanation Converts an ASCII value to a its equivalent character. chr(64) . tells you how similar two strings of text are. you could do it like this: $email_address = "me" . To see what ASCII value the @ symbol returns. Tells you how many words a string has.

str_replace( ) This allows you to replace one string with another. the match was. If you want nine dollar signs. is optional. $search_text). though. $change_to. "<BR>". $user_attempt = "Bill Bates".Home and Learn The first two are the strings you want to compare. $user_attempt. In the example below. 9). so you can leave it out. match_count. –108– . in percentage terms. $changed_text = str_replace($look_for. then you'd use the function like this: $extra_dollars = str_repeat("$". The syntaxt is: str_replace($look_for. print $search_text . The above script will print out the following: 9 90% correct The blank space is counted as a character. match_count). "<BR>". $search_text. The last one. It's counts how many matches it has found. Here's an example that tells the user how accurately they entered a username: $real_username ="Bill Gates". $change_to = "explode". This is optional. for example. $search_text = "The explore function". we're looking for "explore" and want to replace it with "explode". print($percent . print($check) . print $changed_text. $change_to. $look_for = "explore". print $extra_dollars. $percent). The percent tells you how accurate. str_repeat( ) Repeats a character a specified number of times. $check = similar_text($real_username. "% correct").

The length is how many characters in the string: $string_length = strlen("This is some text"). then you have to tell PHP which character in the string to start at. The above line of code returns a value of 17 – the number of character and spaces in the string.How many words found. In which case.com. This is optional. str_word_count( ) Tells you how many words a string has. and "char". The length is how many characters you want to grab. you'll grab all the characters to the end of the string.Beginners PHP So you're looking for one string in the search text. This is the default 1 . then you can leave out "return". Might be useful to someone! strlen( ) Gets the length of a string. suppose you wanted to check if an email address ended in . You can grab a number of character from a string with substr( ).char) If all you want to know is how many words a string has. The return value can be one of three numbers: 0 . The syntax is this: str_word_count(string. print $num_of_words. start. 2 . but the Keys change based on where in the string the words are found.Brings the string back as an array. and replacing it with another.com. Here's an example that checks an email address to see if ends in . –109– . The syntax for substr( ) is this: substr(string. If you miss it out. length) So you provide the function with a string. You could grab the last few characters and check them with an if statement. return .Brings the string back as an array. you can use it like this: $num_of_words = str_word_count("The explore function"). substr( ) This function is short for Substring. For example.

and how you can create your own in PHP. Try this new substr( ) line. provide a negative number. But for now. } Run the script and see which one prints out! You can also start the search from the end of the string.com". This means "grab four characters from your starting position. -4. We'll look at some more string function in later section (date and time functions.Home and Learn $email = "test@test. This means "start 4 characters from the left of the end of the string. } else { print "doesn't end in . This time.4). 4). There's also a length number specified. –110– . In which case. if ($email_end == ". $email_end = substr($email. let's take a closer look at what functions are.com" ) { print "ends in . strlen($email) . we have a figure of minus four. and functions you can use for security purposes). in place of the one above: $email_end = substr($email.com".com".

That's a lot of code to write! " –111– . and want to use again. Here's an example. You separate it because it's nice and handy. That will get rid of the white space in the text box. It's a chunk of code that you think is useful. But it won't check if the text box is blank. But what is a function. Like this: $user_text = trim($_POST['text1'] ). Suppose you need to check text from a textbox. separate from the rest of your code. Functions save you from writing the code over and over. and you want to use it not once but over and over.Beginners PHP PHP Functions You've been working with string functions in the last section. and check each single variable for a blank string. You don't want the textbox to be completely blank! You can use the PHP inbuilt function called trim( ). So if they entered this: " Bill Gates You want to turn it into this: "Bill Gates" But you also want to check if the user entered any text at all. you'll find out. You can add an if statement for that: if ($user_text == "") { error_message = "Blank textbox detected". You want to trim any blank spaces from the left and right of the text that the user entered. and how do you create them? In this section. } But what if you have lots of textboxes on your form? You'd have to have lots of if statements. and references to functions have been made in other section. What is a function? A function is just a segment of code.

It's just like a variable name. And it's more efficient. Using a function means there's less code for you to write. with one if statement that can be used for each blank string you need to check. But first. In between the curly brackets. You can't use trim( ) unless you type out the name. Here's a simple example that just print something out: function display_error_message( ) { print "Error Detetceted". You can call almost anything you like. This is known as "calling" a function. you can create a single function. here's the basic syntax for a function. We'll see how to write a function for the above scenario in a moment. and what you want PHP to trim. Next. } ?> Run your script and see what happens. It's like those inbuilt functions you used.Home and Learn Rather than do that. It doesn't run until you tell it to. Finally. there a print statement. function function_name( ) { } So you start by typing the word function. <?PHP function display_error_message( ) { print "Error Detetceted". You do this by simply typing out the name of your function. The same applies to your own functions – you have to "tell" PHP that you want to use a function that you wrote. Just loading the script won't work. } In the example above. such as trim( ). Try it out with this script: <?PHP function display_error_message( ) { print "Error Detetceted". we've started with function. } display_error_message( ). Try this new version of the script. Whatever you function does goes between the curly brackets. You should find that nothing happens! The reason that nothing happened is because a function is a separate piece of code. you need the two curly brackets as well { }. you type two round brackets ( ). You then need to come up with a name for your function. We've then called this particular function display_error_message. ?> –112– .

display_error_message(). } ?> If you have PHP 4 or above. If a variable can bee seen from anywhere.Beginners PHP After the function. This is set up outside of the function. Run the script. function display_error_message() { print $error_text. it's better to put all of your function either at the top or bottom of your scripts. we have set up a variable called $error_text to hold the text of our error message. In PHP. This refers to where in your scripts a variable can be seen. try this script: –113– . Variable scope and functions There's a thing called scope in programming. But for neatness and readability's sake. and see what happens: <?PHP display_error_message( ). And functions can't see variables if they are not part of the function itself. and you'll get a PHP error message about " Undefined variable". Or better yet. Likewise. This is enough to tell PHP to run our code segment. you should see no difference – the function will still get executed with the name above or below the function. it's said to have global scope. variables inside of functions can't be seen from outside of the function. in a separate PHP file. Try this variation of our script as an example: <?PHP $error_text = "Error Detetceted". Now change your code to this. function display_error_message( ) { print "Error Detetceted". You can then use another inbuilt function called "Include" (which we'll get to soon). we've typed out the name again. } ?> This time.

You pass the variable over to your functions by typing them inside of the round brackets of the function name. function display_error_message($error_text) { print $error_text. print $error_text. display_error_message($error_text). function display_error_message() { $error_text = "Error message". but we're trying to print it from outside the function. we have both the variable and the print statement set up inside of the function. So if you need to examine what is inside of a variable. } ?> –114– . function display_error_message() { $error_text = "Error message". the variable is inside the function. Functions and arguments Functions can be handed variables. } ?> Here. Here's a correct version: <?PHP display_error_message().Home and Learn <?PHP display_error_message(). you need a way to get the variable to the function. } ?> This time. Here's the above script again: <?PHP $error_text = "Error message". so that you can do something with what's inside of them. You still get an error message. The error message now prints. print $error_text.

you are setting up something called an argument. display_error_message( ).Beginners PHP Notice our function now: function display_error_message($error_text) { } The name is the same. don't leave the round brackets empty –115– . The one called $error_text. you need to type it between the round brackets of the function call. This is the variable that we want to do something with. You'll get an error message from PHP something like this: "Warning: Missing argument 1 for display_error_message()" That's telling you that your function has been set up to take an argument. By typing a variable inside of the round brackets. display_error_message($error_text). But try it like this: $error_text = "Error message". The argument is a single variable that you want your function to deal with. That works ok. Here. Now notice how the function is called: $error_text = "Error message". but that you've left the round brackets empty when you tried to call the function. The first line puts something into the variable. But this would do just as well: display_error_message("Error message"). we're putting direct text between the round brackets. In our script. we're typing the name of the variable. to recap: €•To pass something to a function. create an argument €ŽTo call a function that has an argument. but we've put a variable in between the round brackets. But when you want to hand something to a function that has an argument. So.

When you run the script. There has to be something in it. we're not getting the text from a textbox on a form. but just simulating the process. This next script checks two textboxes on a form. Check that what you have left is not a blank string So we want to check that the textbox doesn't just contain this "". Trim any blank spaces from the left and right of the text 3. to this: $user_text = trim(""). Blank text box detected should print out. here it is. Now change this line: $user_text = trim("Bill Gates"). Get the text that a user entered in a textbox on a form 2. Obviously. display_error_message($user_text). you should find that Text OK prints. } } ?> Try it out. Run your script again.Home and Learn A Function to check for blank Textboxes If you remember the script that we wanted to create earlier it was this: 1. This time. like "Bill Gates". –116– . } else { print "Text OK". If you want to try out a version with all the HTML. function display_error_message($user_text) { if ($user_text == "") { print "Blank text box detected". Here's a script that does all three items on our list: <?PHP $user_text = trim("Bill Gates").

Beginners PHP <html> <head> <title>PHP Test</title> </head> <body> <?php $first ="". function display_error_message($user_text) { if ($user_text == "") { print "One or more blank text boxes detected". $second = trim($_POST['second']). } ?> </body> <FORM Method = "POST" action ="formFunction. } else { print "Text boxes OK". display_error_message($second). $second = "".php"> First Name: <INPUT TYPE = "text" name = "first" value ="<?=$first?>"> Surnmae: <INPUT TYPE = "text" name = "second" value ="<?=$second?>"> <input type="submit" name="Submit" value="Submit"> </FORM> </html> –117– . display_error_message($first). } } if ($_SERVER['REQUEST_METHOD'] == 'POST'){ $first = trim($_POST['first']).

Home and Learn The point is. But in both cases. and just let it do its job. here's the two different categories in action: print ("Get on with it!"). if not. } else { $total_charged = $total_spent. But a function like strlen( ) is not. You need something back from it – the length of the string. As an example. and functions where you need to get an answer back. the function calculates the discount. } ?> –118– . that we're using the same function to check for blank text boxes.1. If it is. The print function is an example of a function that you can leave. } return $total_charged. $order_total = calculate_total($total_spent). 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. $total_charged = $discount_total. you may notice that they can be broken down in to two categories: functions that you can leave. You could create a function that is handed the amount spent. Getting values out of functions When you're creating your own functions. $string_length = strlen($string_length). if ($total_spent > 100) { $discount_total = $total_spent .($total_spent * $discount). But you only want to apply the discount if the customer spent over 100 pounds. We're not writing the same code over and over. You just tell it what to print and it gets on with it for you. don't apply the discount. Then check to see if it's over a 100 pounds. and just let them do their jobs. function calculate_total($total_spent) { $discount = 0. print $order_total. Just call our one function as and when needed. Suppose you had a function that worked out a 10 percent discount.

If you're finding this a bit tricky. If you're setting up your function like this then you are asking PHP to return a value from your functions. } else { $total_charged = $total_spent. or not return a value. It depends entirely on your needs.$order_total . $total_charged = $discount_total. calculate_total( ) for us. } The last line is: return $total_charged. were telling PHP to set the answer to the function called calculate_total( ) to whatever is stored in the variable we've called $total_charged. But look at the function itself. and the coloured line at the end: function calculate_total($total_spent) { $discount = 0. if ($total_spent > 100) { $discount_total = $total_spent . which in practice may come from a form on a text box. The next line is our function call: $order_total = calculate_total($total_spent).($total_spent * $discount). The return word tells PHP to return a value. } return $total_charged. The code first sets up a total amount spent.Beginners PHP The lines to concentrate on are the coloured lines. It's this that will get stored in our variable called $order_total. The function call is now on the right of the equals sign ( = ). Here. remember what a function is: a separate piece of code that does some work for you.1. and put the answer into a variable on the left of the equals sign. When it's found an answer. it will try to return a value. The value it returns is whatever you have stored in the variable that comes after the word return. The answer will be stored in the name of your function. or a hidden field: $total_spent = 120. –119– . PHP will go off and calculate your function. To the left of the equals sign is just a normal variable . It can either return a value.

If you just do this. You're not effecting the original. We can then check what is coming back from the function. to check what's in it. change your code to this: –120– . If you ran the previous script. for example: $Variable_Value = 10. you'll notice that the function prints out the same thing twice. rather than letting it just print something out. you can set up the function to accept an argument. if you recall. you'd want to get something back from the function. You'd then type the variable name between the round brackets. That's because the function called example( ) can't see what's inside of the variable called $Variable_Value. example(). and put it in a variable. depending on scope. } then you'll get a PHP error about "undefined variable". it now prints out the number ten. As an example. Another difficult part to understand is how values can change. refers to where in your code a variable can be seen. function example( ) { print $Variable_Value. By Val Functions can be quite hard to get used.Home and Learn In the script above. example($Variable_Value). Like this: <?PHP $Variable_Value = 10. function example($Variable_Value) { print $Variable_Value. when you come to call it. But it's important to bear in mind that you are just handing the function a copy of the variable. if you've never met them before. By Ref. } ?> If you run the code above. Scope. In order for the function to be able to see what’s inside of the variable called $Variable_Value. or not change. we can get a return value. To stop that happening.

one inside of the function. } ?> Here. example($Variable_Value).Beginners PHP <?php $Variable_Value = 10. and don't just want a copy. $Variable_Value . it now print out the following: Before the function call = 10 Inside of the function = 20 After the function call = 20 –121– . The alternative is to NOT pass a copy. we have three print statement: one before the call to the function. When you run the code. $Variable_Value . it will print out this: Before the function call = 10 Inside of the function = 20 After the function call = 10 The important one is After the function call. and NOT the original. Even though we changed the value of $Variable_Value inside of the function. "<BR>". But we're printing out the value of the variable called $Variable_Value each time. $Variable_Value. This tells PHP that you want to make changes to the original. but to refer back to the original. and one after the function call. When you hand a function a copy of a variable. When you run the script. print "Inside of the function = " . Inside of the function. we're adding ten to the value of the variable. function example($Variable_Value) { $Variable_Value = $Variable_Value + 10. Make one small change to your script. it's called passing the variable by value (just a copy). This: function example(&$Variable_Value) { The only addition is a & character before the variable between round brackets. it still print 10 after the function call! That's because the function was handed a copy. print "After the function call = " . print "Before the function call = " . "<BR>".

you type the name of the server variable you want to access. "<BR>". or to ban a particular IP address! (If you run the script on a local machine. we now have a value of 20! So a change to the value of the variable outside the function has been made. The server variables are held in an array (associative). you may get an error for the referrer. When you makes changes to the original like this. Try this script: –122– . $ipAddress = $_SERVER['REMOTE_ADDR'].Home and Learn After the function call. here's some useful inbuilt ones available to you. "<BR>". Unless the answers you're getting back from your function are rather odd. On the left of the equals sign ( = ). then an underscore character ( $_ ). These are useful if you want to log your stats. and which web page the visitor came from. so you can use a foreach loop to get a list of all available ones. you need to put all that on the right hand side of an equals sign. Because you are returning a value. Here's a script to try with those three Server Variables. $browser = $_SERVER['HTTP_USER_AGENT']. print "Browser = " . $browser .) So to get at the values in Server Variables. the IP address. the syntax is this: $_SERVER['Server_Variable'] You start with a dollar sign. $referrer = $_SERVER['HTTP_REFERER']. Surround this with either single or double quotes. This will include things like. $referrer . the browser the visitor is using. Then you add the word SERVER. In between square brackets. print "IP Adress = " . The last of these is VERY useful! PHP Server Variables PHP stores a list of information about the server. Try not to worry about value and reference. print "Referrer = " . that is! To wrap up this introduction to functions. you need a variable to hold the string that is returned. $ipAddress. it's called passing the variable by reference (don't just copy it – remember it).

You're also bringing back something called a HTTP HEADER. and the location of the document. $key_value . should it be displayed as a HTML document.Beginners PHP <?PHP foreach($_SERVER as $key_name => $key_value) { print $key_name .co.homeandlearn. you'll get an error along the lines of "Cannot modify header information. The include function allows you do this. is a useful thing. –123– . you're not just bringing back the web page. and a lot more besides. } ?> What the script does is to loop round all the server variables and print out the keys and values in the SERVER array. HTTP Header() Function When you request a web page be brought back to your browser. This could be whether the page was found (404 errors). This is some extra information. ?> <html> <body> </body> </html> Note how the header code goes before any HTML. here's an example: <?php header("Location: http://www. One of things HTTP HEADER also does is to give status information. date requested. such as type of programme making the request. "<br>". how long the document is. If you put header code after the HTML. or for your PHP scripts.uk/"). If you want to redirect your users to another page. " = " ." INCLUDE( ) Been able to include other files into your HTML code.

type the word include. called include. Now take a look at the code for the PHP page: <HTML> <HEAD> <TITLE>Include files</TITLE> </HEAD> <BODY> <H3>Normal text here </H3> Normal text written in a HTML Editor <H3>Include File here</H3> <?PHP include "textfile. ?> </ BODY> </ HTML > Here the PHP code: <?PHP include "textfile. You could copy and paste the text from the file straight into you HTML.txt. As well as including text. there are two files amongst the ones you downloaded (in the scripts folder). This can save you lots of work. Your filename can either go after a space. you can include HTML.txt" .txt" . Load up the one called include. with links to other areas of your site. or you can put it in round brackets (again. For example. Something like this: –124– . a web page typically contains a menu bar. ?> So in between PHP script tags. After the word include.php and textfile. Or you could use the include( ) function As an example for you to try.php. with the quotes). type the name of the file you want to include on your page. and between quotation marks.Home and Learn Suppose you have a text file that you want to include in a web page that you've already got up and running.

txt (this is also in the scripts folder).php. that would mean having to amend the HTML of all of them. load up the page called links. The new page should be like this: If your site contains lots of pages. you'll see that it's just a HTML table.Beginners PHP Suppose you decide to add a new section to your site.linksPage. This has the include line. If you open up the text file called linksPage.php that is among the files you downloaded (in the scripts folder): you should see the first menu bar.txt. we just did this: <?PHP include "linksPage. To see how it works. To get this table into the PHP page called links. use the include( ) function.txt" ?> –125– . A painful and dreaded task! Instead. that points to another file .

if we had the include line on all pages of out site. print "<BR>".php". You could include those valuable error checking functions that you've stored in one PHP file. The function called doPrint() is in myOtherScript. Put it between the TABLE tags <TR> <TD height="30" valign="middle" bgcolor="#FFFFCC"> <a href="links.php (in the scripts folder that you downloaded at the start of the book). If you open that file.php. This change would then mean that all the pages in the site would be updated! Try it yourself. } ?> –126– . you'll see it's just this: <?PHP function doPrint() { print "This was printed from the myOtherScript. Including scripts You can also use the include( ) function for scripts.Home and Learn The point is. and we had to add a new section. As an example. ?> The above script uses include to include another PHP script . doPrint(). It's just this: <?PHP include "myOtherScript.php">New Section</a> </TD> </TR> Save the page. load up the page called includeScript. You should see a new section added to your menu bar.php". print "This was printed from the includeScript. and then load up links.php (also in the scripts folder).php again.txt. Add the following line to the page called linksPage. Or just use it to cut down on the amount of code in the page.php". we could just change the text file linksPage.myOtherScript.txt. The code is quite simple.

It's only a short section. but it's essential reading! –127– .php in your browser. So.Beginners PHP Load up the page called includeScript. the 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. You should see two lines printed out.

} ?> </head> <BODY> </body> <Form Method = "Post" action ="testSecurity. echo $first_name. This is when somebody enters scripts into your textboxes to launch an attack on your site. and you should see "test name" printed on the page. Take this simple form as an example: <html> <head> <title>Test Attack</title> <?php if ($_SERVER['REQUEST_METHOD'] == 'POST'){ $first_name = $_POST['first_name']. click inside the textbox and enter the following Javascript: <SCRIPT>alert("Scary Script!")</SCRIPT> –128– . then you need to do some security checking on the data that comes in.php. It can be found in the scripts folder and is called testSecurity. That's because of things like Cross-Site Scripting. Now. Load it up and you'll see that it's just a textbox and a Submit button. Click the button.Home and Learn Security Issues and Form Elements If you have things like textboxes and text areas on your forms.php"> <input type = "text" name = "first_name" value ="test name"> <input type="submit" name="Submit" value="Submit"> </Form> </html> This form is one of the files you download.

especially if you have a forum. you should see the following: –129– .Beginners PHP Click the Submit button. But it could have been something worse! Another thing someone could do. Delete everything from your textbox. They could flood your forum with links to harmful or undesirable web sites. and enter this: <A HREF ="nastysite">A Nasty Site</A> When you click Submit this time. You should see this (you need Javascript enabled in your browser): It's just an alert box. is to enter HTML directly into your textboxes. and then watch what happens. Try this as example.

change your PHP script from this. $first_name = htmlspecialchars($first_name). htmlspecialchars() You can use the inbuilt PHP function htmlspecialchars( ) to convert certain HTML into their respective symbols. echo $first_name. and don't convert. that just gives you Bold text. you'd use the HTML special character for this symbol: &lt. To this: $first_name = $_POST['first_name']. is what the htmlspecialchars( ) function does – turns the HTML into the special character codes. And this. You should see this display in the browser: –130– . $first_name = $_POST['first_name']. essentially. If that was your forum. The same is true of this: <A HREF ="nastysite">A Nasty Site</A> This unconverted HTML will turn into an hyperlink. As an example. and turns it into a hyperlink. The new line is in second from the bottom. echo $first_name. It DOESN'T display the left and right pointy brackets. take the following HTML tag: <B>Bold text</B> On a web page. a HTML hyperlink displays above a comments text area. If you actually wanted a left point bracket on your page. and see what happens. it gives you bold text. The browser sees the code above. For example. guess where the link would be? To stop this kind of thing happening.Home and Learn This time. then the browser renders it as HTML – in other words. That's because things like left and right pointy brackets are considered to be HTML. there are a number of techniques you can use. Run your code again. If you enter it into a textbox.

then use this. the German umlaut. So in between the round brackets of htmlspecialchars( ) you type the name of the variable you want to convert to special characters. The difference between the two is that htmlentities( ) will check for non English language characters. such as French accents. htmlentities() A function similar to htmlspecialchars( ) is htmlentities( ). you can do this: $first_name = $_POST['first_name']. Instead of the above. echo $first_name. –131– .Beginners PHP Now it's not treating the hyperlink as HTML – it's turning it into plain text. $first_name = htmlentities($first_name). etc. So if you think your attacker might launch an attack in a language that is not English. The new line in the script is this: $first_name = htmlspecialchars($first_name). PHP takes care of the rest.

You can. echo $first_name. $first_name = strip_tags($first_name). it will look like this: As you can see. "<B>"). It will. When the script is run. If you leave this off then the function will strip all tags. echo $first_name. strip all HTML for you. If it would be OK for people to enter things like bold text or italics.Home and Learn strip_tags( ) A third option is to use the strip_tags( ) function. or that you want to include. –132– . html_tags_to_ignore. tell this function to ignore HTML that you consider harmless. The new line is set up to strip all HTML from the variable called $first_name. html_tags_to_ignore) So the first thing you need to provide the strip_tags( ) function with is the string of text you're trying to check. The second thing. then you'd set up the function like this: $first_name = $_POST['first_name']. as its name suggests. is optional. Here's two example to try: $first_name = $_POST['first_name']. however. $first_name = strip_tags($first_name. Here's the syntax: strip_tags($string. only the text of the HTML is left – A Nasty Site.

Here's what the text area. we're allowing the HTML bold tag through. and the result looks like: Before clicking Submit After clicking Submit So the HTML in the first picture has been allowed through.Beginners PHP So the HTML you want to include goes after a comma. you can see that the text is now in bold. In the second picture. and between quote marks. –133– . In the code above.

But if you take sensible security measure. –134– . you should always use a security technique to thwart an attack. you should be able to defend yourself against most attacks.Home and Learn Summary When you have text coming from a form. it's naïve to think we can thwart every attack. However. and a determined and skilful hacker could probably defeat you.

txt (in the scripts folder). We'll start by opening a plain text file. and take a look at the contents. we take a look at the various way you can manipulate files with PHP. It should look like this: AAS = Alive and smiling ADN = Any day now AEAP = As early as possible AFAIK = As far as I know AFK = Away from keyboard AKA = Also known as It's just a long list of values separated by an equals sign. Open this file up. As it's name suggest. there a few methods you can use. it reads the contents of a file for you. print $file_contents. and on the right its meaning. and storing simple data in a text file can be a good alternative.txt"). We'll open this text file with PHP code. Try this simple script. Not every job requires a database with multiple tables. readfile(file_to_read) To open up a file.Beginners PHP 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. ?> –135– . <?PHP $file_contents =readfile("dictionary. The one we'll start with is readfile( ). Especially if your web host doesn't allow you to have a database! In this section. On the left of the equals sign is an abbreviation. Opening a file There is text file amongst the ones you downloaded at the start of the book called dictionary.

and then a pair of round brackets. Another function that just reads the contents of a file is file_get_contents( ). as above. You can even get it down to one line: print readfile("dictionary. You start by typing readfile.txt"). You should get a web page full of text. print file_get_contents($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). This can be either direct text.txt". The difference for us is the change of name to file_get_contents( ). but make sure it goes in the same folder as your new PHP script. print readfile($file_to_read). It is available in PHP version 4. You don't have to put the file you're trying to read in the same directory. $file_contents =readfile("dictionary. And that's it! Simple.txt". and see what happens. you could do this: $file_to_read = "files/dictionary. or a variable.Home and Learn Save the script with any file name your like. ?> This used in more or less the same way as the readfile( ) function.3 and above. In between the round brackets. hey? Only two lines of code. Run your new code. But here's the part that does the reading. with no separation and no line breaks. –136– . If you had a folder called files in your directory. print readfile($file_to_read).txt"). like this: $file_to_read = "dictionary. Or have any other file reference you want to use. type the name of the file you want to open.txt". Here's an example: <?PHP $file_to_read = "dictionary.

All it does is to set a pointer to the file you want to open. All you're doing is telling PHP to remember the location of the file. } fclose($file_handle). such as setting whether the file is for reading only.Beginners PHP fopen(file_to_open) A better method to open files is with fopen( ). for writing to as well. then we'll explain what's happening: <?PHP $file_handle = fopen("dictionary. The "r" on the end means "open this file for reading only".txt". ?> Run this script and see what happens. Try the script out. "r"). This will read a specified number of character on a single line of text. "<BR>". how do you read the contents of the file? One way is to use fgets( ). You should see something like the following printed out: Resource id #2 Not quite what you were expecting! The reason is that fopen( ) doesn't actually read the contents of a file. ?> –137– . and a few more options. We'll see other options in a moment. print $file_contents. It then returns what's call a file handle. Here's an example: <?PHP $file_contents = fopen("dictionary. "r"). while (!feof($file_handle) ) { $line_of_text = fgets($file_handle). we're printing out each line separately. But now that you've told PHP to remember the location of the file you want to open. fclose($file_contents). you also need to check when the end of the file has been reached. This function gives you more options. This is done with the inbuilt function feof(). print $line_of_text .txt". In the example below. It's typically used to loop round and read each line of text. When you're using fgets( ).

It tells PHP when the end of a file has been reached. 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: while (!feof($file_handle) ) { } –138– . What we're doing here is asking PHP to open up a file. Except. There's the while loop: while ( ) { } And then there's the condition for the while loop: !feof($file_handle) A while loop. 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".txt". You put the file between the round brackets of the function: feof($file_handle) This means. and remember the location. 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.Home and Learn What you should find is that the contents are printed out on separate lines. The location is stored as a file handle. "r"). just goes round and round until you tell it to stop. remember. But how does it work? The first line is this: $file_handle = fopen("dictionary. The next line is tricky! It's a while loop: while (!feof($file_handle) ) { } There's really two parts to this. end of the file referred to in the variable called $file_handle.

then you may get an error if you miss out the line size: fgets($file_handle.2 and above. So we get a line of text from our file." As soon as the end of the file has been reached. The code is a bit tricky. and then place the line into a variable. All this does is to close the open file. the first line is this: $line_of_text = fgets($file_handle). As well as printing out the line of text. But this kind of file opening is useful when you need to read each line of text. when you're meeting it for the first time. Inside the while loop. If you're really packing a lot of information into each line. for example. the while loop will end. "<BR>". –139– . You should always close files that you have opened with fopen(). Again. we could separate each half of the line. The last line in the code is this: fclose($file_handle). We might want to put the abbreviations into one list box and the meanings into another. we need the file handle: fgets($file_handle).Beginners PHP This whole line. line_size). 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. If your version is earlier than this. loop round the file pointed to in $file_handle. The default is 1024. we're adding a HTML line break. reads: "While the end of the file has NOT been reached. The line size needs to be in bytes. We're using the fgets( ) function to get a line of text from our file. But this line size is only optional in PHP version 4. We then print out the line of text: print $line_of_text . then just increase the number for line size. then. With our file. 1024). It tells PHP that the pointer to the file is no longer needed.

But there are other options. If no file exists with your chosen name. "a+"). Here's a fuller list of things you can replace "r" with.txt".txt". The pointer is set to the start of r+ the file. "rb"). But gives you a special warning called x E_WARNING. Same as x but with read access as well. then you can add the "b": $file_handle = fopen("dictionary. b So if you wanted to read and write to the file. "r+"). but used to read and write. x+ In Windows. and append data to the end of the file. Use this to write to a file only. if you want to append data to the end of file when you're writing it back: $file_handle = fopen("dictionary.Home and Learn Options for fopen( ) In the code above. a+ Create a file to write only. If you need to work with binary files (like images). This was why we had the letter "r" in the round brackets of fopen( ): $file_handle = fopen("dictionary. "r").txt". in other words. but with read access as well. we're only reading the file. you'd use this: $file_handle = fopen("dictionary. Or this. –140– . a Doesn't erase contents. then it will create one for you w+ Same as "w".txt". a line break is \r\n. Same as "a". The pointer is set to the start of the file. Mode Meaning Use this to read a file only. The t converts \n line breaks t created on other Operating Systems so that they are readable with Windows Force PHP to open the file in binary mode. r Use this to read and write to a file. Use this to write to a file only. It will erase the entire contents of the w file you have open.

Beginners PHP

Checking if the file exists
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")) { print "file exists"; } else { print "file doesn't exist"; } In between the round brackets of file_exists( ) you type then 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.

Writing to files
When you need to write to files, there are some more functions you need to use. If you have a version of PHP below version 5, then you can use the fwrite() function. But you first need to use fopen( ) 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 $file_handle = fopen("testFile.txt", "w"); $file_contents = "Some test text"; fwrite($file_handle, $file_contents); fclose($file_handle); print "file created and written to"; ?> The new line is the coloured one. First we ask PHP to open the file and create a file handle: $file_handle = fopen("testFile.txt", "w"); 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

–141–

Home and Learn

this name. After a comma, we've typed "w". This tells PHP that the file will be write only. The third line is where we write to the file: fwrite($file_handle, $file_contents); 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 "w" into "a". Run your script a few times, then open the text file. What did you notice? 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() If you have PHP 5, you can use the new function file_put_contents( ) instead of fwrite( ). It is used in the same way, but has an optional third parameter: file_put_contents($file_handle, $file_contents, context); The context option can be FILE_USE_INCLUDE_PATH, FILE_APPEND, LOCK_EX. So to append to the file, just do this: file_put_contents($file_handle, $file_contents, FILE_APPEND);

–142–

Beginners PHP

Working with Comma delimited files (CSV 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.

And here's what the data looks like in a text editor.

–143–

Home and Learn

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: <?PHP $file_handle = fopen("widgets.csv", "r"); while (!feof($file_handle) ) { $line_of_text = fgetcsv($file_handle, 1024); print $line_of_text[0] . $line_of_text[1]. $line_of_text[2] . "<BR>"; } fclose($file_handle); ?> When you run the script, you should see all the lines of text printed out. Here's how it works.

–144–

Beginners PHP

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. $file_handle = fopen("widgets.csv", "r"); while (!feof($file_handle) ) { } Inside the while loop, though, we have our fgetcsv line: $line_of_text = fgetcsv($file_handle, 1024); 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: Widget1, blue, £10 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: $line_of_text[0] $line_of_text[1] $line_of_text[2] To print it all out, we had a this line: print $line_of_text[0] . $line_of_text[1]. $line_of_text[2] . "<BR>"; 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!

Reading a text file line by line into an array – other options
There is another option you can use to place lines of text into an array. In the technique below, we're using the explode( ) string function to create an array from each line of text. Here's the code:

–145–

if you want to split each line and do something different with each part of the line. ?> The first line to note is this: $parts = explode('='. Exactly the same thing happens. $parts[1]. So $parts[0] will hold the abbreviation (AAS) and $parts[1] will hold the meaning. In our code. $line_of_text). "rb"). This is because each line in the dictionary. and placed into an array. In our text file there will only be two positions in the array. If you remember the string section. print $parts[0] .Home and Learn <?PHP $file_handle = fopen("dictionary. This is a good technique to use. while (!feof($file_handle) ) { $line_of_text = fgets($file_handle). so the line will be split again. } fclose($file_handle). $parts = explode('='. "<BR>". –146– . It splits a line of text.txt file looks like this: AAS = Alive and smiling When the explode function is executed. The next time round the while loop. we have used the equals sign ( = ) as a separator. the variable called $parts will be an array.txt". $parts[1]. We then print out both parts of the array with this: print $parts[0] . one for each half of the equals sign. $line_of_text). "<BR>". based on whatever you have provided for the separator. the second line will be read from the text file. you'll also be familiar with the explode function.

"<BR>".php. "<BR>". ?> –147– . $bas . but not the file name <?PHP $dir = dirname("folder/myphp/fileDir.php"). print "directory is: " . This will strip off the name of the file and return the rest of the text between the round brackets of the function. create a new PHP page and save it as fileDir. ?> To get the names of the folders. print "Absolute path is: " . print "File Name is: " . then. This is useful for finding the exact location (relative or absolute) of your scripts or pages. you can use realpath(). you can use the dirname( ) function. Get the Filename only <?php $bas = basename("folder/myphp/fileDir.php"). $absolute_path. $dir . Before you try these out. Get the Directory. ?> To get the exact path of file. Get the Absolute Path of a File <?PHP $absolute_path = realpath("fileDir.Beginners PHP File Locations There are a few inbuilt PHP functions you can use to find out file paths. In between the round brackets of the function. type the name of the file.php"). Here's a few example.

and other security issues. When you type a longer file path in between the round brackets of the function.php/918141 €•http://www.sklar. This could be used to attack your site.com/page/article/owasp-top-ten €’http://www. Final Note Careful when allowing users to upload files from external sources.developer.com/security/writing-secure-php/3/ €‘http://www.onlamp.devshed.Home and Learn If you only need to get at the name of the file.com/pub/a/php/2003/07/31/php_foundations. it will strip off the rest and leave the name of the file.com/c/a/PHP/PHP-Security-Mistakes/ €“http://www.ilovejackdaniels. then use the basename( ) function. For a more in-depth discussion on this.com/lang/article. There a few security implication when working with files.html –148– . these links are quite useful (though we can’t guarantee that the links are still alive!): €•http://www.

then the year. print $today. to get an idea of how it works: <?php $today = date('d-m-y'). But this will be the numerical format. In this section. the separator can be anything you like (within reason). –149– . there is a very long list of things you can put between the round brackets of the function! Try this script. But to use the function. ?> It should print the day of the week first. then the month. But take note of the case. So you can have this instead of a hyphen: $today = date('d:m:y'). because it means the 7th of April in the USA. Unfortunately. we'll take a look at how to process this type of data. There's a list coming up. Change your script to capital letters and watch what happens. it means the 4th of July. So it will print something like: 04-07-2006 This type of date can be very confusing. Or even this: $today = date('d~m~y'). The date( ) function The inbuilt PHP function date( ) is the most widely used method of returning date values. In the UK. however.Beginners PHP Working with Date and Time functions in PHP Knowing how to handle date and time values in PHP will be a useful addition to your programming skills. you first type date followed by the round brackets. Or this: $today = date('d m y'). In between the round brackets you can type a whole host of different date combinations. Also.

but singles are recommended: dates can be a bit quirky. 10 28. 5. 14. 09.0 and above Month Characters Character F m M n t Meaning Full text format of the month Numeric version of the month Short text version of the month Like 'm' but without zeros Number of days in a given month Example March. Miss these out and you'll get errors. They are all case sensitive.1. 9. April 01. Dec 1. then. 10. 0 if no 2006. is a fuller list of the date and time characters. 2nd.Home and Learn Note the single quote marks surrounding the date text. 14. You can use double quotes. 30 or 31 Year Characters Character L y Y Meaning Is it a Leap Year? 4 digit year value 2 digit year value Example 1 if yes. Sunday 1st. 07 Time Characters –150– . Here. but without the zeros Like 'D' but not shortened Ordinal ending for the day of the month Numeric value for day of week Week number of the year Numeric day of the year Example 05. Wed. Feb. 6 is Saturday 12th day of the year 0 to 365 NOTE: W is available in PHP version 4. 05. 20th 0 is Sunday. Day of the week Characters Character d D j l (lowercase 'L') S w W z Meaning Day of the month The day in text format Like 'd'. 2007 06. 31 Mon. Jan. Sun 5. 29. 31 Monday.

15. Example 1 (prints out something like Monday 7th September 2006) <?PHP $today = date('l jS F Y').Beginners PHP Character a A g G h H i s Meaning Morning or Afternoon? Like 'a' but uppercase 12 hour format – no leading zeros 24 hour format – no leading zeros 12 hour format – with zeros 24 HOUR FORMAT – WITH ZEROS Example am or pm AM or PM 1. 12 00. ?> Example 3 (prints out something like "11:25:44 am") –151– . " of " . 9. 09. 28 Feb 2006 15:22:23 +0300 That's quite a lot of characters! Mostly. 23 00 to 59 00 to 59 minutes seconds Other Date and Time Characters Character O T r Meaning Greenwich Meantime offset Time zone of the computer Full formatted date and time using RFC 2822 Example +0300 GMT. print "It's week " . 09. ?> Example 2 (prints out something like "It's week 9 of 2006") <?PHP $today = date('W'). 23 01. Here's a few examples of the way you can use the above. you'll be dipping in and out to find the one you need. 12 0. print $today. $year. EST Tue. $year = date('Y'). $today .

?> getdate( ) Another useful date/time function is getdate. If you leave it out. This will return an array (associative) with all the date and time values. print $time. print $time. For example. The time stamp is optional.Home and Learn <?PHP $time = date('h:i:s a'). You can use it for things like comparing one date to another. ?> Example 4 (prints out something like "23:28 GMT Standard Time") <?PHP $time = date('G:i T'). it gets the values for the current local date and time. The parts of the array are this: seconds minutes hours mday wday mon year yday weekday month 0 (day of the month as a number) (day of the week as a number) (month a number) (year day as a number) (day in text format) (month in text format) (Seconds since the Unix Epoch) Because getdate returns an associative array. you can just do this sort of thing: –152– . Here's the syntax: getdate(time_stamp). comparing how many days have passed since a given date.

$post_date. You can do it like this: <?PHP $post_date = 60. $day_difference = $today['yday'] . and a good reference is the PHP. We've then used "yday" to calculate how many days have elapsed since the last post: $day_difference = $today['yday'] . print $today['mday']. As a further example. and you want to compare that date against today's date. You then type one of the above Keys between quote marks. Working with dates and times can be quite tricky. ?> So we've set up the array using getdate: $today = getdate(). If you look at the previous tables. print $today['wday']. As well as setting out all the date and time functions. suppose you want to work out how many days it's been since a forum member last posted something.Beginners PHP $today = getdate().php.net/manual/en/function.php –153– .date.$post_date.net website. $today = getdate(). there's lots of posts from people with good date/time scripts: http://uk. you've read this value back in. you'll see that "z" means the year day as a number. Print "Days since last post = " . So a value of 60 would mean the 60th day of the year. So whichever part of the array you want to access goes between square brackets. And that you have used this to write the date of the last post in a database: $post_date = date('z'). $day_difference. print $today['yday']. Now.

then you should see a folder like this on your hard drive: If you can see all those files and folder then you already have MySQL installed.mysql. If you installed EasyPHP.Home and Learn PHP and MySQL PHP has the ability to connect to and manipulate databases. We will be working with MySQL databases throughout these lessons. and comes with the EasyPHP software you may have installed at the start of the course.com/downloads/ –154– . If you haven't yet got MySQL. This is a free database system. The most popular database system that is used with PHP is called MySQL. you can download it here: http://dev.

Beginners PHP Click on the Community Edition link.1/en/index. We'll assume that you already have MySQL installed.1/home/mysql/ You should see the phpMyAdmin page display: –155– .mysql.0. Now enter this in your browser's address bar: http://127. Select your operating system from the list. if you have it (Windows users only).0. try this: http://127. But to check that it's up and running using EasyPHP.0. and you'll be taken to a download page.1/mysql/ If it doesn't work.) For instructions on how to install MySQL on your operating system.exe file that you just double click to install.0. then you database system is up and running OK. (Windows user might want to try the Windows (x86) option. This is a setup.html. start EasyPHP and you should see a dialogue box like this: If you have a green light to the right of the MySQL button.com/doc/refman/4. see the online documentation at http://dev.

So you can still follow along with the later tutorials. you're creating a structure like this: –156– . then here's a simple primer.Home and Learn We're going to be creating databases using this. though! If you can't see the page. Again. You might want to bookmark the mysql page. If you're new to the world of databases. Or maybe customer information. we have a few databases amongst the files you downloaded. you need to refer to the documentation to fix this. When you create a database. What is a database and what do they look like? A database is a way to store lots of information. or it's not configured correctly. then you have everything you need. You might want to store the names and addresses of all your contacts. Creating a database using phpMyAdmin You can create all of your database tables and queries using PHP code. However. then either MySQL isn't installed. But if you can see the page OK. it's a good idea to get an understanding of just what it is you'll be creating. or save usernames and passwords for your online forum. But before doing that.

The rows are called Records. When the tables are linked together. We're going to create a simple Address Book.Beginners PHP ID 1 2 Title Mr Mrs First_Name Test Second Name Test Surname The columns (ID. so we'll start by creating one of these using phpMyAdmin. Flat-file database are easier to create and understand. Title. If you just have a single table in your database. Surname) are called Fields. as in the next image: This is where you type a name for your database. Each record is a separate entry.1/home/mysql/ instead. then it's called a flat-file database. So. type http://127. if you have EasyPHP version 2. In a database.1/mysql/ to bring up phpMyAdmin.0. Although it looks a bit muddled. A single database can contain many tables.8 of EasyPHP. However. if you have version 1. You will be taken to a new area: –157– . so type that into the textbox: After you have typed a name for your new database.0. it's said to be a relational database.0. First_Name. type http://127. the part to concentrate on is the textbox under the words create new database. and they can be linked together.0. click the "Create" button.0. you save the information in a Table.

more complex. Another. surname. as it says. To create a new table. You can also type a number for the Fields textbox. remember. type it out exactly as it is below: When you've finished. In fact. address. and will be things like first_name. But the database itself has been created. area will appear: –158– . At the moment. click the Go button. The fields are the columns.Home and Learn In this new area. there are No tables found in the database. but just type 4 in there. You can always add more later. you can create a Table to go in your database. type a name for it in the box at the bottom. etc.

and Address. Click the down arrow to see the following list you can choose from: –159– . the rows are actually the Columns you saw earlier – the Fields. numbers. Setting up Fields in your database tables We have four Fields in our table.Beginners PHP In this new area. Although they are set out in rows in the images above. 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. Each Field needs a name. for numbers. etc? To set the type of data going into a field. you set up the fields in your database. for yes/no values. etc. You can specify whether a field is for text. We'll see how to do that now. you select an item from the Type drop down list. First_Name. Yes/No value. Surname. So go ahead and type the following for your Field names: So we have given each column in our table a name: ID.

Here's the difference between them. and there are four different Text Types to choose from. Integer Values TINYINT SMALLINT Signed: -128 to 127. Unsigned: 0 to 65535 ID – –160– . there is an INT but no Number.Home and Learn As you can see. we want to hold these Types: A number. And that's leaving out things like float and double. We can use INT (meaning integer) for the numbers. used just to identify each record. though. but again. there's quite a lot! But you won't use most them. there are a few Integer Types to choose from. For the values we have in our four fields. This needs to be unique for each record First_Name Text Surname Text Address Text If you look at the list. Unsigned: 0 to 255 Signed: -32768 to 32767.

The MySQL manual says this about the various lengths that each text type can hold: TINYTEXT TEXT MEDIUMTEXT LONGTEXT L+1 byte. We can set it to one of the INT values. where L < 2^32 This in not terribly helpful for beginners! So what does it mean. We're using this just to identify a record (row). But which one? If we set ID to TINYINT. IF you have more than 65 and half thousand friends. If you used SMALLINT. you can go from 0 to positive 255." The translated values for each are approximately: TINYTEXT TEXT MEDIUMTEXT LONGTEXT 256 bytes 64 KiloBytes 16 MegaBytes 4 GigaBytes –161– . For our address book. so it will need a different number for each. you need to be aware of the signed ranges. "The length of the string. where L < 2^8 L+2 bytes. the L + 1 part means. so we'll use SMALLINT. where L < 2^16 L+3 bytes. for example.Beginners PHP MEDIUMINT INT BIGINT Signed: -8388608 to 8388607. we have an ID field. Unsigned: 0 to 18446744073709551615 The signed and unsigned are for minus and non minus values. plus 1 byte to store the value. If you didn't need the minus value. Unsigned: 0 to 16777215 Signed: -2147483648 to 2147483647. where L < 2^24 L+4 bytes. Each record will be unique. So if you need to store negative values. If you were using a TINYINT value. Unsigned: 0 to 4294967295 Signed: -9223372036854775808. then you need a different INT type. We'll assume that you don't. Well. you can go from minus 128 to positive 127. then you'd run in to problem if you tried to store more than 255 records. you'd have problems if you tried to stored the details of friend number 65536. Text Types The length for the text types can be quite confusing.

0. The blank spaces get added to the right of your text: "TEXT " "TENLETTERS" VARCHAR Like CHAR.3 was 255. After this it's jumped to 65. but the rest of the characters are not padded with blank spaces. use CHAR or VARCHAR. For our fields. 535. CHAR You specify how many characters you want the field to hold. you can also use CHAR and VARCHAR to store your text. With VARCHAR. and one of those will be a blank space. then. there is also an extra byte that records how long your text is. So there's no sense in setting a postcode field to hold 4 gigabytes! Instead. But if you only use 4 of them. for a UK postcode you don’t need more than 9 characters. These are quite useful. For example. The maximum value before MySQL 5. we'll use the following Types: ID First_Name Surname Address SMALLINT VARCHAR VARCHAR TINYTEXT So select these from your Types drop down list: –162– . The maximum value is 255.Home and Learn To confuse the issue even more. the rest of the 10 characters will be blank spaces. For example: CHAR(10) This field can then hold a maximum of ten characters. if you know how many characters you want to store.

then you can't leave it blank when you come to adding records to your database. as we have an ID field. and choose Auto Increment from the Extra drop down list: –163– . "Should the field contain anything?" If you set a field to NOT NULL. They are set to unique values. Extra This is where you can set an auto increment value. So. Primary keys are not terribly important for flat-file databases like ours. just in case it's left blank when adding a record? If so. This means adding one to the previous record number. and Unique. The other Field settings we'll take a look at are these: NULL This is an important field in database terminology. and want to link information. If you leave it blank for VARCHAR. But they are important when you have more than one table. Unique is useful for those fields when there can't be any duplicate values. MySQL will take care of updating it for us The three icons are Primary Key. An index is useful for sorting information in your tables. set a primary key for the ID field by selecting the radio button. as they speed things up. Then we don't have to worry about this field. Default Do you want to add anything to the field.Beginners PHP We've only set Lengths for the VARCHAR TYPES. you'll get a default value of 1 character. Otherwise you'll get errors. like our ID field. type it in here. Index. It essentially means. This is ideal for us.

Home and Learn Your field screen then. All we want to do is to add one record to the table. and specified the kind of information that will be going into each field (the columns). We'll then use PHP code to add some more Adding records to a MySQL Table To insert a new record to your table. minus the parts we've ignored. You'll be taken back to the Structure screen. should look like this: Bear in mind what we've done here: we've just set up the fields for our table. Click the Save button on the fields screen. We haven't yet added any information to the table. Don't worry if it looks a bit confusing. select the Insert Link at the top of the page: –164– . There should be a lot more information there now.

The address area is a lot bigger. Go ahead and enter the following information for the Value textboxes: ID: First_Name Surname Address 1 Test Name 12 Test Street –165– . because we used TINYTEXT. But look at the lengths of the textboxes under the Value.Beginners PHP When you click on Insert. The sizes are determined by the length of the Fields. our four fields are there: ID. you type your data in the textboxes under the Value heading. Surname. This one: As you can see. you'll be taken to a new area. First_Name. To enter a new record in your table. and Address.

click the Go button at the bottom of the screen. And that's it – you now have a database to work with. and is automatically created for you for all new databases. To see where it has been saved. Double click the folder called mysql. When you double click this folder. You will be returned to the Structure screen. you should see a few files there: –166– . This is the same as the database name. navigate to your PHP folder on your hard drive.Home and Learn Your screen should then look like this: Finally. This is where all of your databases are stored: Notice the folder name in the image above: addressbook. Inside this folder will be one called data.

We can move on to doing just that . and you should then be able to access the tables in the database with PHP code.Beginners PHP Notice the files names – they are the same as the tables you create. they ARE the tables. you can upload this folder and its contents to your data folder. In other words. If you have PHP web space.accessing this database with some PHP code. –167– .

and delete records. To open our database.Home and Learn Manipulating a MySQL database with PHP In this section. Open a connection to MySQL itself 2.net. Specify the database we want to open 3. we'll stay with the inbuilt functions for versions earlier than PHP 5. Here's the code we're going to be using.Open a connection to MySQL The first job is to actually connect to MySQL. Using PHP code. you'll first open the database. –168– . a lot more were added as well! Here. you'll see how to manipulate the simple Address Book database you've just created. mysql_connect( ) does exactly that. Step 1 . It is recommended that you don't dash off and use this on the internet! This is for learning purposes only. In PHP version 5. You'll also need to know how to add new records. But this is just to get your started. <?PHP $user_name = "root". you can then read its contents. it's well worth researching the newer database functions. But if you have version 5. Close the connection Let's do Step 1 on the list. $password = "". though. A good place to start is php. we'll use the following inbuilt functions: mysql_connect( ) mysql_select_db() mysql_close() The approached we'll take has three steps: 1. a database has to be opened. First. Once the database is open. before you can do anything with it How to access a MySQL database with PHP code PHP has a lot of inbuilt functions you can use to manipulate databases. As it's name suggests. $database = "addressbook".

The username we're trying here is "root" and the password is blank. Hopefully. Or as variables.0. You don't need to change these.0. These are the MySQL defaults. –169– .0. $password). $server = "127. and putting something in them: $user_name = "root". $database = "addressbook". followed by the round brackets. $password = "".0. like this: mysql_connect('127.1'. $user_name. and your MySQL password. your MySQL username. $password). So you type the name of the function first (mysql_connect ). $user_name. $user_name. you need three things: the name of your server.1". $password).1".0. The first four lines are just setting up variables. you won't have any errors. These can be entered directly. But the line that connects to MySQL is this: mysql_connect($server. print "Connection to the Server opened".0. And that's all you need to get you connected to MySQL. ?> Save your work and try it out on your server.Beginners PHP $server = "127.1".0. In between the round brackets. ''). like we did at first: $user_name = "root". mysql_connect($server. That's Step 2 on our list. $password = "". $server = "127. mysql_connect($server. 'root'. But we haven't connected to the database yet.0. in most cases.

to something like this: $database = "addressbook2".1". You use the mysql_select_db( ) function to specify which database you want to open. mysql_connect($server. We now need to do something with this variable. You can use some logic to test if the database was found. The function then returns a true/false value. $password = "". Change the last two lines of your code to this: $db_found = mysql_select_db($database).0. if your database can't be found then a value of false is returned. So add this new line to your code (second from bottom): $user_name = "root". $password). If it finds your database. print "Connection to the Server opened". $database = "addressbook". } else { print "Database NOT Found". a value of true is returned.Home and Learn Step 2 .0. $server = "127. $user_name.Specify the database we want to open In our code. } Now change the database name from this: $database = "addressbook". if ($db_found) { print "Database Found". we set up a variable with the name of our database: $database = "addressbook". –170– . $db_found = mysql_select_db($database).

if ($db_found) { print "Database Found " . $password).0. The resource link identifier (file handle) goes after the name of the database you want to open. and connected to a database. } else { print "Database NOT Found " . $db_handle. But there's another option you can use for mysql_select_db – something called a resource link identifier.0. When we connect to the database.Close the connection Closing a connection to a database is quite easy. and putting it into a variable called $db_handle. $db_handle). $database = "addressbook". $db_handle = mysql_connect($server. $db_handle). If you've used a file handle. $password). $db_found = mysql_select_db($database. } So when we connect to the database.Beginners PHP Run your code again. it's time to close the connection. and you should see Database NOT Found printed out (unless you have a database called addressbook2). $password = "". we're now using this: $db_handle = mysql_connect($server. Now that we've connected to MySQL. You use it like this: $user_name = "root". Step 3 . $server = "127. It's just a file handle that you used in an earlier section (opening text files). It's just the same as before. You can then use this file handle to refer to your database connection. you just do this: –171– . $user_name. Change the database name back to addressbook. $user_name.1". except we're returning a value from the mysql_connect function. we can use this file handle: $db_found = mysql_select_db($database. as above. $db_handle.

the more trickier the SQL is.Home and Learn mysql_close($db_handle). $db_handle = mysql_connect($server. it's fairly straightforward. Here what your code should now look like: <?PHP $user_name = "root". $database = "addressbook". it's time to look at how you can access the data in the database. To specify which records you want. you don't need to bother. and print them out to the page. we'll add a line to close our connection. } else { print "Database NOT Found ". if ($db_found) { print "Database Found ". now that we have a connection to our database. $password). Otherwise. $user_name. is to read all the records.0. though. This stands for Structured Query Language. } ?> Now that we've got a connection to the database. It's recommended that you take the file handle approach. you use something called SQL. What we want to do. non-coding language that uses words like SELECT and WHERE. At it's simplest level. the technique is usually to loop round and find the ones you want. We'll start with something simple though. $password = "". Reading records from a database To read records from a database. This is a natural. added to the PHP script you already have: –172– .0. So. $db_handle).1". mysql_close($db_handle). $db_found = mysql_select_db($database. But the more complex the database. Here's some new code. $server = "127. That's what we'll be doing from now on.

"<BR>". $db_found = mysql_select_db($database. $db_handle = mysql_connect($server. $user_name. "<BR>". } mysql_close($db_handle). $password = "". print $db_field['Address'] .1".) 1 Test Name 12 Test Street The first line in the new code is this: $SQL = "SELECT * FROM tb_address_book". You should find that the address you added in a previous section is printed out.Beginners PHP <?PHP $user_name = "root". } else { print "Database NOT Found ". if ($db_found) { $SQL = "SELECT * FROM tb_address_book". $server = "127. "<BR>". print $db_field['First_Name'] . } ?> Before we go through the new code to see what's happening. –173– . $db_handle). "<BR>". (We only have one record at the moment.0. $result = mysql_query($SQL). run your script.0. $password). $database = "addressbook". while ($db_field = mysql_fetch_assoc($result)) { print $db_field['ID'] . print $db_field['Surname'] . mysql_close($db_handle).

but we need to pass it to another inbuilt function: mysql_query( ) The mysql_query( ) function is used to send a SQL query to your database. But we're putting into it a long string. The asterisk (*) means "All Records". So the whole line reads: "SELECT all the records FROM the table called Table_Name" You don’t have to select all the records from your database. then the function will return a value. and you'll meet more of them as you go along. This is a SQL statement. If you want to grab all of the records from a table in a database. Table_Name is the name of a table in your database. The keywords in the lines above are SELECT and FROM. The first line was this: $SQL = "SELECT * FROM tb_address_book". There are a lot more SQL commands to get used to. you use the SELECT word. so the above line could be written: Select * From Table_Name But your SQL statements are easier to read if you type the keywords in uppercase letters. Structured Query Language SQL (pronounced SEEKwel). Here's a brief run down on SQL. Back to the code. SO we have a SQL statement. we can specify that in our SQL String: "SELECT First_Name. The basics are quite easy to learn. This –174– .Home and Learn The $SQL is just a normal variable. For example. we're just selecting all the records from our table. Surname FROM tb_address_book". is a way to query and manipulate databases. only the First_Name and Surname columns from the database will be returned. You can just select the columns that you need. Like this: SELECT * FROM Table_Name SQL is not case sensitive. If you have typed out your SQL correctly. then. if we wanted to select just the first name and surname columns from this table. When this SQL statement is executed. For now.

we're putting it all into a variable called $db_field. without anything between the round brackets: while ( ){ print $db_field['ID'] . In between the round brackets of mysql_fetch_assoc we have typed the name of our file handle – the one that was pointing to the results of SQL statement. This is done automatically for you. "<BR>". As in "associative array". The file handle returned in our $result variable just points to the results. the line was this: $result = mysql_query($SQL). –175– . In our code. we had this inside a while loop: $db_field = mysql_fetch_assoc($result) The inbuilt function we're using to bring results back is this: mysql_fetch_assoc($result) The assoc part means Associative. The Key part of the array is all the Column names from our database tables. or a file handle. It doesn't actually bring anything back. So we're asking that the results be brought back in an array format. Here's our loop. So it's this format: Array['One'] = Array['Two'] = Array['Three]' = And not this: Array[1] = Array[2] = Array[3] = When the mysql_fetch_assoc function returns an array. Because we're using the SELECT keyword. Remember: an associative array is one where the keys are text. 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. the value returned by will be a file handle. false. To bring back the data.Beginners PHP value will be true.

is this: while ($db_field = mysql_fetch_assoc($result)) { print $db_field['ID'] . The array will contain all the records that were returned in Step 2 4. Use mysql_query( ) to bring back the records we've specified in Step 1 3. If all that is confusing. "<BR>". just remember the format: Array_Name[Table_Coulmn_Name] = Value_From_Record Our whole while loop. $db_field['Surname'] and $db_field['Address']. "<BR>". Step 3 was this: $db_field = mysql_fetch_assoc($result) –176– . in the code: $SQL = "SELECT * FROM tb_address_book". print $db_field['Address'] . let's go through the steps we've used to access the records from our table: 1. "<BR>". then. "<BR>". print $db_field['First_Name'] . print $db_field['Address'] . We're also adding a HTML line break at the end. "<BR>". } So we're printing whatever the value is in the array position $db_field['ID']. "<BR>". Step 2 was this: $result = mysql_query($SQL).Home and Learn print $db_field['First_Name'] . print $db_field['Surname'] . Set up a SQL Statement that can be used to get the records from the database table 2. "<BR>". just for printing purposes. Loop round all the data in the array using a While loop Step 1 was this. Use mysql_fetch_assoc( ) to set up an array. $db_field['First_Name']. print $db_field['Surname'] . } Because that is a bit complex.

open this script up. print $db_field['Address'] . $db_found = mysql_select_db($database. $user_name. $password). "<BR>". So. Set up a SQL Statement that can be used to add records to the database table 4. In fact. $password = "". "<BR>". $server = "127. $database = "addressbook". but this time to add records to the table 5. and save it under a different file name. The only thing that needs to change is your SQL statement. you can use your script from the previous section. "<BR>". Use mysql_query( ) again. –177– . "<BR>". Specify the database we want to open 3. } If you're still confused. Open a connection to MySQL 2. we'll adapt the code to add more records to our database table. print $db_field['Surname'] . $db_handle = mysql_connect($server.0.1". print $db_field['First_Name'] .0. It's the same code as before. In the next section. study the code and go over this section. The steps we're going to be taking are these: 1. Close the connection We've already done steps 1 and 2 on the list. Adding records to a database table To add records to a table in your database.Beginners PHP And Step 4 was this: while ( ){ print $db_field['ID'] . $db_handle). Then delete the following lines in italics below: <?PHP $user_name = "root". you use more or less the same code as previously.

while ($db_field = mysql_fetch_assoc($result)) { print $db_field['ID'] . mysql_close($db_handle). $db_handle = mysql_connect($server. "<BR>". } mysql_close($db_handle).0. $database = "addressbook". otherwise you'll get errors when we run the code. $db_found = mysql_select_db($database. } ?> So you're deleting the SQL statement. Replace the SQL line with this: $SQL = "INSERT INTO tb_address_book (First_Name.0. $result = mysql_query($SQL). 'Microsoft')". But your new code should look like this: <?PHP $user_name = "root". $user_name. $password). $db_handle).1". } else { print "Database NOT Found ". if ($db_found) { –178– . print $db_field['Address'] . print $db_field['First_Name'] . $server = "127. The double and single quotes need to be entered exactly as they are above. 'gates'. Surname. "<BR>". "<BR>". "<BR>". print $db_field['Surname'] . and the While loop.Home and Learn if ($db_found) { $SQL = "SELECT * FROM tb_address_book". Address) VALUES ('bill'. $password = "".

Address) VALUES ('bill'. open a connection to the database. Surname. mysql_close($db_handle). type a pair of round brackets. For us. you can add the values you want to insert. That's because the ID column was the one we set up to be an auto-incrementing number. this is the table that we've called tb_address_book. you can use the INSERT statement. but we'll stick with something simple: adding new values to all of our table columns. This can be in any case you like: upper. INSERT INTO … VALUES To add records to your database. Surname. lower or a mix. You start by typing the words "INSERT INTO".Beginners PHP $SQL = "INSERT INTO tb_address_book (First_Name. statement. print "Records added to the database". The next thing you need is the name of a table to insert your new values into. 'Microsoft')". and then execute the SQL query. We don't need to worry about this column because MySQL will take care of adding 1 to this field for us. $result = mysql_query($SQL). Following the name of your table. 'gates'. There are plenty of ways to use this statement. It's easier for you to read if it's in uppercase letters. Inside the round brackets. mysql_close($db_handle). Now that you've specified which table you want to insert values into. and rather long. The only difference is the new SQL statement! What the code does is to set up some variables. Address) Notice how we haven't included the ID column from our table. –179– . } ?> You met all of this code from the previous section. and specified your column names. } else { print "Database NOT Found ". you can type the names of the columns in your table: INSERT INTO tb_address_book (First_Name. Let's have a look at the new.

and 'Microsoft' with values of your own. 'gates'. If you use things like text boxes and text areas on your forms. Each value should be separated by a comma. But inside of the values round brackets. Inside of these brackets. like we've done. You can use either direct text. you type the word "VALUES" after the round brackets of your column names: INSERT INTO tb_address_book (First_Name. which we'll see how to do later. You should find that you now have two records in your database table. But you can use an inbuilt PHP function for this: mysql_real_escape_string() We'll see how this works in a moment. Using HTML Forms with your Database You can use a HTML form to query your databases. The syntax is really this (The SQL keywords are in italics): INSERT INTO table_name ( Columns ) VALUES ( values for columns) But try your code out now. 'gates'. Surname. But there are special security considerations you need to bear in mind. So our whole line reads: $SQL = "INSERT INTO tb_address_book (First_Name. you need to take care. but let's get some practical work done. There is a file amongst the ones you downloaded called magicTest. Things like single quotes need to be escaped. Notice how we've surrounded all of our text with double quotes. Run your script again to add your new record to the database.php (in the –180– .Home and Learn To add values. we've used single quotes. Surname. This is because of an attacks like SQL injection. you type another pair of round brackets. Address) VALUES After the word "VALUES". Now run your other script to read the values back out. you can type your values. Exercise Replace the values 'bill'. or variables. Address) VALUES ('bill'. 'Microsoft')". You can even get these values straight from your HTML form. and see if it's all working properly. We'll look at those issues in this section.

That way. As an example. You should see the name printed exactly as it is in the text box.0. Now load up the your PHP script with the text box and the button. in which case the data directory is here: –181– . These characters can be used to launch a SQL injection attack on your database. Then save the changes. When you installed your server. click your button again. This is a list of all the various settings to do with PHP itself. there will be a file called php. You should see this printed: O \' Connor So PHP has put a backslash before the single quote. with your server running. or do a search for it). Save the entire membertest folder to your data directory in your mysql folder. so good. Search for this line: magic_quotes_gpc = Off Change the Off to On. For EasyPHP users this will be at: C:\PHP\EasyPHP1-8\mysql\data Unless you have EasyPHP version 2. You should see a text box and a button. With O' Connor still in the text box. Typed the following name into the text box: O'Connor Now click the button. if it's not already on. then PHP will add the backslash to all single and double quotes. try this. If this is set to On. So far. we'll load up a database and a script. Now. an attacker's life is made more difficult.ini. Locate this file called php. Inside this folder there is a one called membertest. Amongst the files you downloaded there is a folder called databases. if you're running SQL on your databases. These are already prepared for you. Open it up in a text editor.ini (in the folder called apache.Beginners PHP scripts folder). But what's going on? Magic Quotes Characters like single and double quotes can be very dangerous. Load this script in your browser. So the makers of PHP came up with a function called magic_quotes_gpc.

An attacker will test to see if any syntax error messages can be returned. There is also a button on the form. The attacker can then go ahead with further probes. of course! It's so that you can thwart them.php in your root folder. The four fields are: ID username password email So the username is test1.Home and Learn C:\Program Files\EasyPHP 2.ini file.php (in the scripts folder). –182– .com. Now set magic_quotes_gpc = On back to magic_quotes_gpc = Off in your php. and you should see following print out: 1 test1 test1 test1@test1. Place magicTest2. suppose you were naïve enough to have a database table exactly like that one. the password is test1. Along with the database folder there is a PHP script called magicTest2. and the database. this means that the author of the script has not dealt with single/double quotes correctly.0b1\mysql\data Change the C to whatever letter your hard drive is. We'll use this script. one for a password. SQL injection When you open the magicTest2. Enter the following in the email address text box: test1@test1. you'll see three textboxes: one for a username.com These correspond to the four fields in the database. and one for an email address. If so.com Click the button. and the email address is test1@test1. Now.php page in your browser. to teach you about SQL injection. Not so that you can launch your own attacks.

Because it's a stray single quote. Next. Only this time. After the word "WHERE". with the single quotes: hi' OR 'x'='x When you click the Submit button. Can the table and field names be guessed? Can a username and password be guessed? It's this kind of attack that you want to thwart. you'll get a syntax error. The value we want to check is coming from the variable called $email. Enter the following into the email address box: ' OR ''=' –183– . in our case). type the following. In the email address textbox. When an email address is entered in the text box on our form. further attacks will be launched. Type it exactly as it is. The SQL this time has a WHERE clause added. followed by the value you want to check. that single quote is not being escaped. Try this last one. password and email address are printed out! The attacker is trying to find out whether or not the SQL can be manipulated. Something like this: Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource Because Magic Quotes are off. Try this. you should find that there are no errors. When you type that extra single quote on the end. The line in our new script that is doing the damage is the one: $SQL = "SELECT * FROM members WHERE email = '$email' ".com' Now click the Submit button.Beginners PHP Try your script again. The WHERE clause is used when you want to limit the results to only records that you need. What you should find is that an error message is indeed returned. It's this syntax error that an attacker is looking for. You then have an equals sign. this value goes straight into the variable without any checks. and that the username. This is then run on the database. This is surrounded with single quotes. If the answer is yes. that will be added to the SQL. you type a column name from your database (email. add a single quote to the end of the test email address in the textbox: test1@test1. the attacker will try to add some SQL to yours.

The one to use for this kind of attack is: mysql_real_escape_string( ) Between the round brackets. there is another script like the one you've just tried.php (in the same scripts folder). Now. Again. you should see this added to the code: $email = mysql_real_escape_string($email. the details are printed out. you MUST use some inbuilt PHP functions. Try the above attacks again.com' What you should find is that the following gets returned: test1@test1. If you open this up in your text editor. followed by an optional database handle. Enter the following in the email address text box (with the single quote on the end): test1@test1. But you need to use the function on all variables or data that will be used in your SQL. a backslash is added. This time.Home and Learn Now click Submit. you type the string you need to check. The OR clause is set to a blank string. This is because an OR clause has been added. if any of the listed escape characters have been used. the $email variable is being checked for any of the following: \x00 \n \r \ ' " \x1a If any of the above characters are found. So you should do this kind of thing: –184– .com\' So the single quote has had a backslash added to it. To test this out. The point is that the dangerous SQL doesn't get executed. $db_handle). you shouldn't be able to get in. Meaning that the records will be brought back if it's a valid email address or not! To stop this kind of attack. This one is called magicTest3. Try the new script.

with the recommended code added. Pay attention to where the new lines go: after you have opened a connection to your database. so that you can see it in action. } // Connect $link = mysql_connect('mysql_host'. bold is ours): <?php // Quote variable to make safe function quote_smart($value) { // Stripslashes if (get_magic_quotes_gpc()) { $value = stripslashes($value). 'mysql_user'. The PHP manual recommends the following sample script.Beginners PHP $username = mysql_real_escape_string($username. $email = mysql_real_escape_string($email. mysql_query($query). mysql_real_escape_string($value) . quote_smart($_POST['username']). ?> We have adapted the magicTest3 script. See if you can figure out how the new additions work. $db_handle).php. // Make a safe query $query = sprintf("SELECT * FROM users WHERE user=%s AND password=%s". $password = mysql_real_escape_string($password. Open the script and study the code. "'". quote_smart($_POST['password'])). Examine the code in the new script. $db_handle). The new script is magicTest4. when working with SQL (all comments are theirs. 'mysql_password') OR die(mysql_error()). } return $value. $db_handle). But the PHP manual script above can be found at: –185– . } // Quote if not integer if (!is_numeric($value)) { $value = "'" .

mysql-real-escape-string. If it's not. $valid_other = "£$^&_@#~". But if you don't want your databases attacked.Home and Learn http://us3.php. dealing with SQL injection attacks. and handling all those escape characters. then you can display an error message.php As well as using mysql_real_escape_string( ). you'll need to use the other function you saw earlier. you might have this in your script: $valid_chars = "abcdefghijklmnopqrstuvwxyz". It can be a lot of work. An excellent walkthrough of security blunders can be found at: http://www. For example. $valid_nums = "1234567890".net/manual/en/function.htmlspecialchars(). You can then use some Conditional Logic to test if the character the user entered was on your list.sitepoint.com/article/php-security-blunders –186– . you HAVE to defend yourself! Limit the charcters that a user can enter Another security technique that some advocate is to limit the characters that can be entered. in the forms section .

UNIQUE id (ID) )". just so that you can get an idea of how they work. Then you type the name of the table you want to create. So you start with the Clause CREATE TABLE. However. which field is the primary keys. But you'll meet more SQL when we start our walkthroughs.Beginners PHP Other things you can do with SQL We'll go through some of the other things you can do with SQL. and that the PHP code to open a connection has already been written (you saw how to do this in a previous section): $SQL="CREATE TABLE AddressBook ( ID int(7) NOT NULL auto_increment.tizag.php Create a Table using SQL You can create tables using SQL (and whole databases). their data types. you use the CREATE keyword (known as a clause. Surname varchar(50) NOT NULL. This assumes that the database itself already exists. followed by some formatting. doing it this way is not recommended: you tend to forget which fields are in the table. An excellent introduction to SQL can be found here: http://www. and which ones are set to NULL values. First_Name varchar(50) NOT NULL. In between round brackets. All of the walkthroughs use databases and SQL. –187– . the first field being set up is this: ID int(7) NOT NULL auto_increment.com/sqlTutorial/index. If you can get to grips with visual tools like phpMyAdmin then so much the better. and specify the fields you want to go in the table. PRIMARY KEY (ID). Here's the SQL to create the simple address book we've been using. To create a table then. in database speak). mysql_query($SQL). email varchar(50). In the code above. you type the name of your table Columns.

We've specified that the record to change should have the First_Name of Bill and the Surname of Gates. Notice that there is only one comma in the line. We're also setting up three other columns here: First_Name. UNIQUE id (ID) The primary key is used for things like joining data from one table to the data from another. then your coding life gets easier! Updating a record in a table You can also update a record in your table. The data type is an integer that is no longer that 7 digits. you can go ahead and execute it: mysql_query($SQL). you type the name of the Column you want to change. After the word SET. Here's an example: $SQL = "UPDATE AddressBook SET email = 'new_email_address' WHERE First_Name = 'Bill' AND Surname = 'Gates'". You can also update an entire column. tricky work for you as a PHP programmer. and change all the values: UPDATE AddressBook SET Surname = LOWER(Surname). We've set this to our ID field. Creating tables like this means a lot of extra. Primary keys don't have duplicate values. Surname. whenever a new record is added. but email can be. the word UPDATE is used for this. Then you need another Keyword: SET. First_Name and Surname can't be left blank ( NOT NULL). After the word UPDATE. At the end. Once you've written your SQL statement. you need the name of the table you want to update.Home and Learn The column name will be ID. If you can use a tool to do the job for you. But notice the WHERE clause. and that it can't be left blank. Not surprisingly. NOT NULL means you want something in this field. –188– . and email. In the SQL above. we have these two lines: PRIMARY KEY (ID). The comma separates each field you want to create in your table. The ID number will be auto incremented. we're changing the email column. so we've set this to be a UNIQUE field.

Beginners PHP Again. we've typed the column name again. When the following code is run. you don't want to return all the records from your table. Most of the time. Deleting a record in a table If you want to delete a record in a table.com will be returned. we've used the inbuild SQL function LOWER( ). If we do. Then you type the name of the table. This changes a value to lower case letters. We've SET the column name as Surname. In the code above. Using WHERE limits the records returned from a SQL statement. only the records that have an email field of me@me. $SQL = "SELECT * FROM AddressBook WHERE email = 'me@me.com' ". In the SQL below. use WHERE. we might have more than one Bill Gates in the table. After an equals sign. make sure you read the security section. use the DELETE Keyword. But before you do. you need to specify which record you want to delete. only the record that has number 7 in the ID field will be deleted. This will just slow things down unnecessarily. you need FROM. After the DELETE word. everybody called Bill Gates will be deleted! A better solution is to use a unique field from your table. This will ensure that all the text in the Surname column gets changed to lower case. Using WHERE to limit the data returned You can add a WHERE part to your SQL. Like this: $SQL = "DELETE FROM AddressBook WHERE First_Name = 'Bill' AND Surname = 'Gates'". It's a good idea to make sure your WHERE clause is going to be a unique value. Especially if you have a large number of records. Next. Now. Instead. we've specified that the AddressBook table should be updated. we're using WHERE to bring back only the matching records from the AddressBook table. such as an ID field: $SQL = "DELETE FROM AddressBook WHERE ID = '7' ". In between the round brackets of the function. You can specify more fields in your WHERE clause: –189– .

and is well worth the effort. Getting the hang of WHERE can really speed up your database access.Home and Learn $SQL = "SELECT * FROM AddressBook WHERE First_Name = 'Bill' AND Surname = 'Gates'". we're specifying that all the records from the AddressBook table should be returned WHERE the ID column is greater than or equal to 10. In the SQL statement above. we'll take you through some fuller projects. and explain the code. In the next sections. –190– . Only records that have First_Name value of Bill AND a Surname value of Gates will be returned. we've used the AND operator as well. An awareness of the security issues involved is also a must. You can also use the operators you saw in the variables section: $SQL = "SELECT * FROM AddressBook WHERE ID >= '10' ". First up is a username and password system. In this SQL statement. and the things you need to consider when working on bigger projects like this.

where users are authenticated by means of a username and password. you can fire up your server and try it out. It will look like this: –191– . You'll see how to do that in this walkthrough. The database table has a test username and password set. a tutorial site. after all.) In this walkthrough. The login page The first script to take a look at in the login folder is login. We're using a simple table. Also. But let's get started. What we don't offer is a complete login script. which is one of the folders you downloaded at the start of the book. Once the user is logged in successfully. with three fields: an ID field. This is. make sure cookies are enabled in your browser. and well see how it works. just like you did before. there are some scripts already prepared. and a field for the password (called L2). Of course. he or she can then gain access to the restricted areas of the site. so that you can try it out. when you come to implement your own login pages. The username is usernameTest and the password is passwordTest. so as not to complicate the tutorials. These can be found in the login folder.php. Copy this to the data directory of you mysql folder. For the walkthrough. But you'll want to add more fields.Beginners PHP User Authentication Walkthrough A lot of sites add a members section. a field for the username (called L1). You need to read these! A word about the database used for this section The database we've set up for these tutorials is as simple as they come. and we'd much rather help you develop your own scripts. You'll see why. later. we'll explore some of the things you need to bear in mind when creating a username/password section on your site. It consists of a table called login. (It's in the scripts folder. as well as a submit button. The database can be found in the databases folder. Other things you need to consider before implementing a login section on your site are discussed at the end of this section. Open up this script in a text editor. What you'll see is a simple login page with textboxes for username and password.

We'll add something to this variable. $num_rows = 0.?> This is for displaying error messages for the user. There's nothing special about it. if an error occurs. The next part of the code is just the SQL checking function you met earlier. The first few line of the script.Home and Learn The HTML for this form can be seen at the bottom of the login. The $errorMessage variable is an important one. just set up some variables: $uname = "". We'll then check to see if it's blank or not. After this code. we check to see if the form has been POSTED or not (was the Submit button clicked): if ($_SERVER['REQUEST_METHOD'] == 'POST') { } Most of our code goes between the curly brackets of this if statement. $errorMessage = "".php script that you have (hopefully) by now opened. But notice that there's a PHP print statement in the HTML Body section: <?PHP print $errorMessage. The first thing to do is to get the username and password from the textboxes: –192– . $pword = "". though. This aims to prevent SQL injection attacks.

With the username and password sanitised. $db_handle = mysql_connect($server. $user_name. $database = "login". If the database was found. We check for this in the next lines: if ($db_found) { } else { $errorMessage = "Error logging on".0. $pword = htmlspecialchars($pword). We're selecting all the records in the database where the incoming username and password match the database table fields called L1 and L2: $SQL = "SELECT * FROM login WHERE L1 = $uname AND L2 = $pword". $pword = $_POST['password']. $db_handle). $db_handle). we can then set up a SQL command. $server = "127. $pass_word). $db_found = mysql_select_db($database. We then deal with any unwanted HTML (scripting attacks): $uname = htmlspecialchars($uname). These next two lines call the function at the top of the code: $uname = quote_smart($uname. If the database was found.0.1". Next. then some text is added to the error message variable.Beginners PHP $uname = $_POST['username']. we attempt to connect to the database: $user_name = "root". strip the incoming text of any unwanted characters (SQL Injection attacks). The value in $result will either be true (if any records are returned) or false (if none are –193– . $pword = quote_smart($pword. then the variable called $db_found will be true. $db_handle). issue the SQL command using mysql_query( ): $result = mysql_query($SQL). $pass_word = "". Next. We need to check what is returned by the mysql_query() function. } If the database isn't found.

} else { $errorMessage= "Invalid Logon". } In the above code. If so. A session is simply the time spent at a particular site or sites. put something in the error message variable: if ($result) { } else { $errorMessage = "Error logging on". You can store values with sessions. The inbuilt function mysql_num_rows( ) is used for this. If no rows were returned. When you close your browser. assume that it doesn't matter if login details are the same. you want to credit forum users with the correct posts. If not. then it does matter. If you have a website where each user has to be unique. and these values will be available to all pages on the site. We're checking to see if there were any errors when the SQL command was issued against the database table. Next. the sessions will end. For the purpose of this tutorial. where people are posting and replying to the input of others. the number of rows returned could be greater than 1. it doesn't really matter if 2 or more people have the same login details. you can use something called a Session. That would mean that 2 or more people have the same username and password. After all. you can see how many rows were returned from the database table. If it is. } If the SQL command was issued successfully. if ($num_rows > 0) { $errorMessage= "logged on ". then you have a successful logon.Home and Learn returned). then you obviously want to check if $num_rows = 1. then it's invalid. There –194– . then that tells you that there's something wrong with either the username or password. we test the $num_rows variable to see if it's greater than zero. But for things like forums. Setting a Session So that a user can be remembered across different web pages. $num_rows = mysql_num_rows($result). For some websites.

header ("Location: page1. then the user is OK. header ("Location: page1.php"). In the previous code.php"). $_SESSION['login'] = "1". } The code checks to see if the number of rows returned from a SQL command is greater than zero. After the script runs. you use this: $_SESSION[ ] In between the square brackets of $_SESSION. } else { $errorMessage= "Invalid Logon". you type the name of your variable. but we're only interested in saving a value so that it can be referred to across different pages. the part that checked if the user was OK was this: if ($num_rows > 0) { $errorMessage= "logged on ". you'll have a session variable called 'login' that is set to a value of 1. You can then use the "header" function to redirect the user to the page on your site for members. you need to issue the start command: session_start(). But the code in the login. To set up a session variable. It's this: if ($num_rows > 0) { session_start().php in the code above. page1. This starts a PHP session. Like all variable names.Beginners PHP are quite a lot of ways to use sessions. } What the code does is to set up a session variable. To set up a session variable that you can use to store values. If it is. if the user is OK. Storing values in the session variable is just the same as storing values in a normal variable: $_SESSION['login'] = "1". –195– . The value in the variable will be 1. if the user logs on successfully.php script is slightly different. you can call it almost anything you like.

then you should be able to log on whether cookies are set or not. we issue the "start session" command: session_start(). } Here. A note of caution here. in that case. This line: session. there's a good chance that you can't set this to zero. We're using the same session name (login). } else { $errorMessage = "Invalid Login". and how to use them.devpapers. but this time we set it to a blank string. A blank string means that the user hasn't logged on successfully. PHP attempts to save the session ID as a cookie. can be found here: http://www. But the next line puts something different in to the session variable: $_SESSION['login'] = ''. Especially if you have web hosting with someone else.com/article/335 –196– . the code is this: if ($num_rows > 0) { session_start(). But it only does this if a line in php. we'll check for a blank string. A good run down on cookies. session_start(). the script above refuses to work! This is because when you use session_start.ini from your Apache server is set. Next.Home and Learn For the else part of the if statement. so we'll redirect them to the login page. header ("Location: page1. $_SESSION['login'] = ''. The problem is. If you switch cookies off in your browser. This is a long string of letters and numbers. $_SESSION['login'] = "1". PHP sends the browser something called a session ID.php"). is to check whether cookies are enabled or not. we add something to the error message variable: $errorMessage = "Invalid Login".use_cookies = 1 If you set this value to 0. If the user tries to gain access to a restricted part of the site. The solution.

you'll see this code at the top: <?PHP session_start(). If it is. set a session variable to a blank string €šBuilt up an error message throughout the code But the point about setting a session variable is so that you can then check its value when users go to other pages on your site. you can check the session variable that you set up on the login page. you first start the session: session_start(). if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) { header ("Location: login. And that's about it for the login script. Next comes a complex If statement: –197– . To stop this happening. then the user is redirected to the login page. set a session variable to 1 €™If no rows were returned. If you open up the page called page1. what's to stop non members from simply typing the address of the page in their browsers? If you haven't set any checks.Beginners PHP You'll also see a script that you can adapt to check if cookies have been enabled on the browser. We'll see how to do that now. whether they are a member or not. then the page will load. Here's a run down on what we did: €”Got the username and password from textboxes on a form €•Opened a connection to a database €–Validated the username and password €—Checked to see if any rows were returned from the database €˜If rows were returned. Checking if the user is logged on or not On all pages of your site that you want to secure. you'll need to check if the user was successfully logged on or not. } ?> This checks to see if the session called login is set. and that it's not a blank string.php"). After all. In the script.php.

and that it's not a blank string. you can send them somewhere else. Or. for us. Log Out You'll also want to ensure that your users can log out successfully. Fortunately. If everything is OK then the user will see the HTML code below the PHP at the top. } In between the round brackets of the If statement. This is quite easy. That code. " If the value in the round brackets of isset is indeed false. otherwise you'll get "header" errors.php"). "if the value of the isset function is false . This is followed by the inbuilt isset() function: if ( !(isset( ) ) { } This says. And it needs to go before any HTML code.. was the redirection line.. we have the NOT operator. we check to see if a session variable has been set. Is the user has logged in successfully. –198– . "If NOT isset". as the only thing you need to do is to destroy the session. "AND session login DOES NOT EQUAL a blank string". If it's not. In other words. then the code between the curly brackets { } gets executed. a value of 1 will be set inside of this variable.Home and Learn if ( ) { header ("Location: login. But we also need to check the session variable for a blank string. So we have and AND part to the statement: && $_SESSION['login'] != '' This says. What we have between the round brackets of isset is this: ($_SESSION['login']) That's just our session variable from the login page. PHP has an inbuilt function for that: session_destroy(). But you need to put that PHP code at the top of every page that you want to protect. You can't put it in the head section.

php. the log out script will be executed. and wants to sign up. you'll see quite a lot of it is code that you've already met. you can add a link to a "sign up" page. though: <?PHP session_start(). you can add a link on your page1.php>Log out</A> When the user clicks this link.Beginners PHP When this function is executed. Open up the signup. The next lines are these: $uname = $_POST['username'].php page. Register a new user If the user is new to the site. and take a look at the code. though. and then checking it for unwanted tags.php page. and you'll see some code already there. We'll now walk you through what it all does. all the session variables that you set up for the user will be destroyed. –199– . $pLength = strlen($pword). session_destroy(). Then we check that the form has been POSTED. If you try to reload page1. even though you've been using sessions throughout your pages! So that the user can log out.php. is test that the username and password are of the correct length. It starts with the function that checks for dangerous SQL characters. It's just this. Open up the page called page2.php page: <A HREF = page2. ?> Quite bizarrely. you'll be redirected to the login page. $uname = htmlspecialchars($uname). you have to start the session first. When you open up the code for the signup. You don't want a malicious user trying to inject megabytes of text! $uLength = strlen($uname). $pword = htmlspecialchars($pword). like we did before. We're just getting the username and password from the form. $pword = $_POST['password']. The next thing you need to do.

then the user will see the text of the error message displayed. Inside of the if statement for the error message check. $pass_word). we can check to see if the error message is blank: if ($errorMessage == "") { } If it's blank.Home and Learn if ($uLength >= 10 && $uLength <= 20) { $errorMessage = "". } What we're doing here is using the inbuilt function strlen( ) to get the length of the string. If it's not OK. Before checking the username and password against the database. If they are not ok. "<BR>". if ($db_found) { } –200– . "<BR>". $pass_word = "". we add some text for the error message. "Password must be between 8 and 16 characters" . If they are ok. $user_name.. $db_handle). else statements to check that the username and password are between certain values. } if ($pLength >= 8 && $pLength <= 16) { $errorMessage = "". the variable called $errorMessage is left blank.0. In which case the rest of the code is executed. We then use if . then everything is ok. } else { $errorMessage = $errorMessage .0. $server = "127.1". we just set up the database code like we did before: $user_name = "root". } else { $errorMessage = $errorMessage . $db_found = mysql_select_db($database. $database = "login". $db_handle = mysql_connect($server. "Username must be between 10 and 20 characters" .

But in that case. We check the value of $num_rows in an if . then the variable called $num_rows will be greater than zero. perhaps we shouldn't be using a username to log people in?) If the value in the variable $num_rows is still zero. else statement. (But there are security considerations to bear in mind here. then it's ok: the malicious user can simply read usernames from forum posts. we can then set the session variable: session_start(). then we can go ahead and add the user to the database: $SQL = "INSERT INTO login (L1. $pword)". Do you really want to tell a malicious user that a username has already been taken? If it's for a forum. If it is. $result = mysql_query($SQL). After the user has been added to the database. if ($num_rows > 0) { $errorMessage = "Username already taken". In fact. then we need to check if the username has already been taken: $SQL = "SELECT * FROM login WHERE L1 = $uname".. (L1 is the name of the username field in the table.Beginners PHP We're just checking that the database can be found. This means that the user can then start using the site straight away. } else { } The code attempts to select all the records from the table where a match with the username is found. $_SESSION['login'] = "1". Here. If the username has already been taken.) If any records are returned.. $num_rows = mysql_num_rows($result). $result = mysql_query($SQL). L2) VALUES ($uname. mysql_close($db_handle). then we can add something to the error message variable. we use the SQL command INSERT INTO to add a new record to the database. we redirect them to a different page on the site: –201– . The session variable called login will be set to 1.

Home and Learn

header ("Location: page1.php"); Our new user is now a member!

Other considerations
The above sign up script is fairly simple, and there other things to consider. Here's a few of them. Validation Some sites ask you to provide an email address when signing up. (An alarming number of them!) They then send you your login details and confirmation via email, with perhaps a hyperlink that you need to click on to verify the details. You would then enter the verification code or codes before you can start using the site. To do this, you would need to add more fields to your database table - an email address field and a verified field. The verified field would be set to NO, by default. You could then check this field from all pages of your site. If it still says NO, then the user hasn't yet confirmed the login details. In which case, don't let them in. The verified field would only get set to YES if the user went to the page mentioned in the email and entered the correct details. This type of script is more complex to set up, and tends to be more frustrating for the user. And there is always a sneaking suspicion that your email address is being sold off to the nearest spammer! Passwords If you need to save a password to your database table, then you have to encrypt the details. If you look at the signup script, you'll notice the use of this function: md5(pword) The inbuilt function md5() returns a 32-character hexadecimal number, based on the string you type between its round brackets. You then save this "hash" number to your password field. Or do it all in one go, with your SQL statement:
$SQL = "INSERT INTO login (L1, L2) VALUES ($uname, md5($pword))";

The L1 field is for the username and the L2 field for the password. The VALUE for the password now goes between the round brackets of md5()

–202–

Beginners PHP

When you check the password field on the login page, you'd then do this: $SQL = "SELECT * FROM login WHERE L1 = $uname AND L2 = md5($pword)"; Again, the password goes between the round brackets of md5(). But storing passwords in encrypted format is highly recommended!

Some more things worth considering on your login/signup pages: €›Test if the users is already logged in. That way, they can't sign up repeatedly without closing down the browser €œSet a cookie for logins, instead of using sessions. You then need to write code to read the cookie data back for every protected page on your site. €•Collect other information, and store then in your database tables: date and time of login, IP address, etc €žUser's forget their usernames and password. You'll need a link to send them the details. However, don't forget to add some extra security here! Something like a password reminder (memorable date, favourite teacher, etc) is recommended. €ŸEnumeration attacks are quite a common way for malicious users to try and gain access to your site. This is when the attacker can simply sit at his/her pc screen and enter the username and password over and over again, looking for "error message" clues. To thwart this type of attack, you might want to limit how long a user has to log on to your site. A good way to do this is by setting a session to end after so many minutes. This page is worth exploring, for such script ideas: http://www.weberdev.com/get_example4267.html

Conclusion Although our login/sign up 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!

–203–

Home and Learn

Build your own Survey Application
The Survey web application consists of 5 PHP files and a database. You'll see what they all do as we go along. But there are separate sections: A section where you can set a question for your visitors; a section that allows visitors to vote on your question; and a section where the results can be viewed. The survey itself looks like this, on the page:

When you click the Vote button, your choice will be recorded in the database. If you click the "View Results" button, you'll see this:

You'll learn how to code for all of this. But we're going to start with setting a question for the survey. Off we go.

Set a Question for your Survey
To set a question for your survey, you simply type the question into textboxes on a form. You then set the options that a visitor can choose from. The Form to set a question looks like this:

–204–

Beginners PHP

To test this out, locate the folder called survey, which is amongst the files and folders you downloaded at the start of the book (in the scripts folder). Copy the entire survey folder over to your www folder. Now load up the setQuestion.php page in your browser by typing: 127.0.0.1/survey/setQuestion.php You should see the web page as above that allows you to set a question. This is just a simple HTML form that has no special formatting applied, and so looks a bit messy! But you can use this to add questions to your Survey database. But don't click the button on the form yet, or you'll get an error message. First, copy the database folder called surveytest to your mysql/data folder. You data folder should then look like this:

–205–

Home and Learn

To see if the database has been copied ok, type this into the address bar of your browser (this assumes that your server is up and running): http://127.0.0.1/mysql/ If you have EasyPHP version 2.0, however, you need to type this instead: http://127.0.0.1/home/mysql/ What you're trying to do is to bring up the phpMyAdmin page. This one:

We'll now take a look at how the database is set up, because it's the key to understanding how the survey web application works.

The database
From the left hand side of the phpMyAdmin screen, under "Please select a database", have a look at the items on the drop down list. You should see one called surveytest.

–206–

If you can see surveytest. select it from the drop down list.Beginners PHP If you can't see surveytest there. and you'll see the Structure for this Table: –207– . You should see the names of two tables appear: Click on tblQuestions. it means you haven't copied the surveytest folder to the correct place.

Home and Learn Under the Table heading. and are important. you'll see the two tables in this database: answers and tblQuestions. They are: QID Question qA qB qC –208– . as in the image below: You will be taken to the Field names and Rows in the table: The Field names run from left to right. Click on the Browse icon for tblQuestions.

phpMyAdmin doesn't enforce this. You don't have to worry about this field. the unique field (the primary key) is the ID field. If you look at the matching row (q4) in the tblQuestions table you'll see that the question was: Do you believe in UFOs? (These answers were entered by us . It also speeds things up.it's not real data!) Now that you have a good idea about how the database works. along with the qA.you have to code for that yourself!) The A. and to avoid having too many fields in a single table. and q4. You do this when you want to keep data separate. This QID field is the Primary Key in this table. –209– . (NOTE: If you have some knowledge about databases. This allows you to select all the records in both tables based on the QID field. Joining data from a primary key in one table to a foreign key in another is common technique in database creation. For example. and C fields in the answers table record how many people voted for each option of your question. q2. 127 people voted for option B. qB. along with the same values from the tblQuestions table: A. Then click on Browse at the top. In our example database. is also in the answers table. This same field. QID. Unfortunately. So if you delete a row from one table. and C. You can then use this QID field to identify each row in the table. one for each question. for question four (q4) 28 people voted for option A. B.Beginners PHP The tblQuestions table above has four rows of data. This means that the data in this field has to be unique. qC fields. let's go through the code that sets a question. The QID field is the one to pay attention to. You should see this: In the answers table. This matching field in the answers table is something called a foreign key. the corresponding row in another table won't get deleted . B. Take a look at the answers table by clicking the link on the left hand side. and 52 people voted for option C. So. you'll know about Referential Integrity. This is just an auto incrementing number that you used in an earlier section. You just pull all the records that match. you can say "Select all the records in both tables where the QID field equals q1". we can keep the questions and answers separate. The values in the sample table are q1. But notice that the QID field is also there. q3. in database terminology.

(For simplicity's sake. Next. so we're going to have to increment the values with code. $boolLastRow = mysql_data_seek($result. and take a look at the code. open up the file called setQuestion. Most of it is code you've already met.1)). Because the primary key is a unique field. But we've made our own unique field to be used as a primary key. $result = mysql_query($SQL). then. $question_Number = 'q' . check for any unwanted script tags. $next_Q_Number = ltrim($qID. $qID = $row[0]. In the first two sections we just get the data entered in the textboxes on the form (the questions and three possible options). –210– . You'll see how to code for this in the next section. you'll get an error.) The code. and then open up a connection to the database. The idea is that we get the last number value from the QID field. As the comments say. 'q'). We need to do this because the primary key doesn't auto increment. we're getting the last question number from the tblQuestions table. $row = mysql_fetch_row($result). start off by getting all the records from the tblQuestions table: $SQL = "Select * FROM tblQuestions". $next_Q_Number.Home and Learn Setting a question – the code Using your favourite text editor. $next_Q_Number++. then add 1 to it. there's no checking to see if the value we write back to the database is indeed unique. $numRows = mysql_num_rows($result). we try to run this query: $result = mysql_query($SQL).php again. If it isn't. ($numRows . the auto increment feature of MySQL would have added one to the primary key for us. The first new code is this: //============================================ // GET THE LAST QUESTION NUMBER //============================================ $SQL = "Select * FROM tblQuestions".

–211– . This allows you to jump to any row in a table. You've met the inbuilt function mysql_fetch_row( ) before. Between the round brackets of the function. The code that moves the internal pointer to the last row in the database is this: $boolLastRow = mysql_data_seek($result.to increment it. This variable will then hold the last QID value from the table.Beginners PHP We could check here if the value in the variable called $result is true. It fetches a row of data. We need to get the number of rows so that we can move the pointer to the last row in the database. $next_Q_Number. (Another thing for you to do!) But we're keeping things simple. $next_Q_Number++. The QID field is at position zero in the array (it's the first field in the database). If it wasn't. Once we've moved the pointer to the last row in the table. We're using an inbuilt PHP function called mysql_data_seek( ). and manipulate the data. Otherwise.1. But we're leaving out the error checking here. and puts it all in to an array. This is then put in to the variable we've called $qID. The format we're using for the QID field is to type a letter "q" followed by a number. Remember: we're trying to add 1 to the value in the QID field . you first type the name of your resource ($result. we can just add 1 to the number then join that number to the letter "q". So we just use $row[0] to return the value. We want to get this last row so that we can check the QID field. The next few lines do exactly that: $next_Q_Number = ltrim($qID. we'd get an error about no such row found. $qID = $row[0]. The next thing to do is to get the number of rows in the table: $numRows = mysql_num_rows($result). if this returns a value of false. We're returning all this to a boolean variable called $boolLastRow. Then. You can then access the array. 'q'). $question_Number = 'q' . so you can see how all this works. after a comma. To increment the QID field. we can fetch the data back: $row = mysql_fetch_row($result). You can write an error message. The count with mysql_data_seek( ) starts at zero. we could display an error. so we're deducting one from the number of rows in our table. for us).1)). you put the row that you want to jump to: $numRows . ($numRows .

You should be able to figure out what it does: adds the data into the Field names mentioned in the first round brackets. will hold the number of votes. B. C) VALUES ('$question_Number'. remember. qB. $next_Q_Number. '$answerC')". 0. '$answerB'. This leaves just the number itself. qC) VALUES ('$question_Number'. and ensures that the default options are all filled in. We've covered quite a lot of ground in a short space of time. we run the SQL query: $result = mysql_query($SQL). A. it's an INSERT INTO command. qA. The VALUES between the round brackets are: '$question_Number'. The first thing to do is to add the question to the tblQuestions table. 0. We start them off at zero because nobody has voted yet! And that's about it for setting the question. B and C. 0. You've met code like this in a previous section. This adds the new number to the letter "q". A. 0)". € Created two tables in the same database €¡Had a primary key in one table that is joined to a foreign key in the other table –212– . The final line joins the new data back together: $question_Number = 'q' . But the next three values are all zero. You can then increment this number (next_Q_Number++). so let's review what we did. The next SQL command is slightly different: $SQL = "INSERT INTO answers (QID. The next two sections use the INSERT INTO command to add the new question to the database. The rather long SQL line that does that is this: $SQL = "INSERT INTO tblquestions (QID. '$question'. To update the table. This sets up the answers table. 0. and then stores it in a variable called $question_Number.Home and Learn We use the ltrim function to strip off the letter "q". Question. Again. '$answerA'. 0 The value inside of $question_Number will be the QID number. It's this question number that will get written to the QID fields in both the tblQuestions table and the answers table. but note that we're now updating the answers table.

1/survey/survey.php in your text editor. there is also a button that allows you to view the results. –213– .php You should see this: All we have here is a question.0.Beginners PHP €¢Wrote code to move an internal pointer to the last record in a table €£Returned a specified row. Adding a Survey to your page The survey itslef can be found in the survey folder and is called survey. To see the code for the survey. you select an answer and click the button. On the page. To vote. open up survey. The first line you'll see is this: include 'sqlSurvey. and three possible answers.0. Let's see how it all works.php'. When you do. and incremented a value to be used as a unique key €¤Inserted a new record into two tables. you're taken to another page which thanks you for voting. We'll use this technique again when we create a forum. let's move on to the survey itself.php. using the same field in both Probably the most important thing to learn in this section is how to join separate tables together using a primary/foreign key combination. Open up the this page in a browser by typing the following address: 127. For now.

$SQL = "SELECT * FROM tblquestions WHERE tblquestions. The important part of the SQL line is this: WHERE tblquestions. The survey code can see this variable because of the include directive. The variable called $SQL is in the include file. The data from the SQL is then placed into an array called $db_field. This is the QID field from the tblQuestions table. and you'll see that it's just a SQL command. Save the file. So it knows what's inside of it. or q1. That's enough to pull the question and answers from the table! But although the file is included on the first line. The code is this: $qNum = 'q4'. the only thing you have to change is this value. Only two lines long! The first line sets the question number. the code inside of it doesn't get run till a little later. You've met all this before. Change 'q4' to one of the other three values in the table: q3. This SQL is used to pull a question from the database. and reload survey. Open up this file (also in the survey folder). Try it. After that.php in your browser. To set a new question. so we won't go into it. You can get at these values like this: –214– . The next few lines just set up some variables.QID = '$qNum'". we can put the values into an array with the next line (though you should write could for false values inside of $result): $db_field = mysql_fetch_assoc($result). q2. The part of the code that uses the include file is this: $result = mysql_query($SQL). we add the code that opens up the database.QID = '$qNum' We're saying select all the records WHERE the QID field matches the value in the variable called $qNum. and put default values in them.Home and Learn The include file is an important one. If mysql_query( ) succeeds. You should see the question and answers change.

we can put these into the HTML on the page. Question. Once we have the question and the answers. ?> The "print $answerA" part will just add a value of checked or unchecked to the radio button. and qC. $B = $db_field['qB']. we're returning the values from the following fields in the table: QID. ?> <P> <INPUT TYPE = 'Radio' Name ='q' value= 'B' <?PHP print $answerB. The first is this: <FORM NAME ="form1" METHOD ="GET" ACTION ="process.Beginners PHP $qID = $db_field['QID']. qB.php"> <?PHP print $question. depending on whether it was selected or not. ?>><?PHP print $B. ?> This is the value that we got from the field in the tblQuestions table. ?>><?PHP print $A. $A = $db_field['qA']. There are two HTML forms on the page. ?>><?PHP print $C. The code for the answers is then added to the radio button on the form: value= 'A' <?PHP print $answerA. ?>><?PHP print $A. ?> <P> <INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Click here to vote"> </FORM> The question from our code is placed on the page with this line: <?PHP print $question. We've put these into variables of their own. ?> <P> <INPUT TYPE = 'Radio' Name ='q' value= 'C' <?PHP print $answerC. qA. An answer is added to the radio button like this: –215– . $question = $db_field['Question']. ?> <P> <INPUT TYPE = 'Radio' Name ='q' value= 'A' <?PHP print $answerA. Here. $C = $db_field['qC'].

But one more thing to notice: both forms use the GET method to hand data to the next page. If you open up the code for the process. We'll take a look at that in a moment. though. you'll see that the checking is done via a session variable. but notice the second Form on the page: <FORM NAME ="form2" METHOD ="GET" ACTION ="viewResults. session_start(). ?> Whatever data we pulled from the A "field" in the table will end up in the variable called $A.php.php page. As well as adding the vote to the database. You met this code during the username/password walkthrough. But there is a crucial HTML form element in the form code: <INPUT TYPE = "Hidden" Name = "h1" VALUE = <?PHP print $qID. We can then use this value to pull the correct records from the two tables.php page (in the survey folder). ?>> This sends the QID number to the viewResults page. the user will be sent to a new page. ?>> </FORM> This is for the "View Results" page. we're sending it to a page called process. You'll see how this works soon.Home and Learn <?PHP print $A. When this button is clicked. you're recording the vote and adding it the database. If the button is clicked. it goes to a new page: viewResults. if ((isset($_SESSION['hasVoted']))) { //Already Voted } else { –216– . Behind the scenes. Now let's move on to the code for the process.php. This is then printed to the page. Add the Vote to the database When the Vote button is clicked. you'll probably want to implement some sort of check to prevent people from voting over and over again.php"> <INPUT TYPE = "Submit" Name = "Submit2" VALUE = "View results"> <INPUT TYPE = "Hidden" Name = "h1" VALUE = <?PHP print $qID.

If you have cookies disabled then the session variable won't work. B or C. a message of "You've already voted" will be displayed. then the else part of the if statement is executed. The first line of this is another if statement: if (isset($_GET['Submit1']) && isset($_GET['q'])) { } Here's we're checking for two things: was the Submit button called Submit1 clicked on the previous page. This just gets which radio button was clicked. After the database has been successfully opened. The next line is where we add the record to the answers table in our database: $SQL = "UPDATE answers SET $selected_radio = $selected_radio + 1". In which case. then a vote from this user has already been added to the database. like we did before. a message is displayed. though. –217– . The next few lines open a connection to the database. In which case. If all went OK. and we're placing a value of "1" into it. and you can vote over and over again! You might want to check that cookies are enabled in the browser. then we can assume that the button was clicked but the user didn't select a radio button. and has the radio button data been handed over to this page (the radio button data will be in the variable called 'q')? If the answer to both questions is Yes then we can go ahead and process the data. If no session has been set. we have this: $_SESSION['hasVoted'] = '1'. and check if the session variable called hasVoted has been set. This is then placed into the variable called $selected_radio. this message is displayed: print "You didn't selected a voting option!". The value comes from the HTML form. If it has. This is our "hasVoted" session variable. if the answer is No. and will be A.) So we start a session. the first line of the new if statement to get executed is this: $selected_radio = $_GET['q'].Beginners PHP //Process the Vote } (NOTE: Session variables work by sending you an ID as a cookie. If the user tries to vote again.

and print out a message: "Thanks for voting". you should make sure that the correct record is being updated. We can then use the SET keyword to set just that column from the table. And that's it . You'll notice that we're not making sure to move to the end of the records in the answers table (which we should do). for us). You can add a "back" link to the HTML. Because the variable called $selected_radio will contain only A. –218– . B or C. B or C we can just add 1 to whatever is currently there: SET $selected_radio = $selected_radio + 1". Viewing the results of the survey On the survey. This will be either A. After that.php page. We're taking shortcuts for simplicity's sake. you type the name of the table you want to UPDATE (answers. We only want to update the field that was passed to the page in the "q" variable. the user will see something like this: The lines represents how many people voted for a particular option. there is a button that can be clicked to View the Results. If this button is clicked. This is not a good idea! In your own code.Home and Learn Here.a vote has been added to the table. we have the number as a percentage. and what the option was. we close the connection to the database. or do anything else you like with your page. Or perhaps you could add a link so that the results of the voting can be viewed? We'll take a look at the code for the results page now. but trusting MySQL to do it for us. which are the column names from the answers table. we're using the SQL command UPDATE. After the word UPDATE. After the table is updated.

we check to see if the Submit button was clicked on the previous page. The VALUE of the h1 hidden element is coming from the $qID variable. How many people voted for a particular option? To see how many people voted for A. We can use this value to pull records from the tables. which the next two lines do: $SQL = "SELECT * FROM tblquestions.php"> <INPUT TYPE = "Submit" Name = "Submit2" VALUE = "View results"> <INPUT TYPE = "Hidden" Name = "h1" VALUE = <?PHP print $qID. if (isset($_GET['Submit2'])) { $qNum = $_GET['h1']. we first have to get that value from the viewResults. The Hidden form element had the NAME "h1". and puts values into variables.php page (in the survey folder).php page so that the correct results can be displayed. survey. The rest of the code pulls the data from the table. The HTML form was this: <FORM NAME ="form2" METHOD ="GET" ACTION ="viewResults.php.php page. If it was then we can GET the hidden value: $qNum = $_GET['h1']. depending on how many votes were cast for an option.QID = '$qNum'". We need to pass this QID number over to the viewResults. If you open up the code for viewResults.Beginners PHP On the previous page. It's this NAME that goes between the square brackets of $_GET. answers WHERE tblquestions.QID AND answers. ?>> </FORM> The value in the variable $qID (part of the Hidden HTML form element) is coming from the PHP code you saw earlier. –219– . B or C. We'll keep the two separate. } First.QID = answers. you'll see there's quite a lot there! But most of the code is taken up with manipulating the red. This will be the QID field in the database tables tblQuestions and answers. for explanation purposes. This is the QID field that is in both the questions and answers tables in our database.jpg graphic! We're just stretching a red line.

the answers A. we're selecting all the records from two tables: SELECT * FROM tblquestions. $qA = $db_field['qA']. followed by a dot. $answerA = $db_field['A']. If you look at the values in the square brackets. Here. $answerC = $db_field['C']. we have this: tblquestions. qB and qC). we put the results into an array: $db_field = mysql_fetch_assoc($result). This is present in both tables.QID The name of the table goes first. –220– . ready for displaying on the page. B and C. Hopefully! After the SQL has been run. The WHERE clause is quite tricky: WHERE tblquestions. but go over it a few times and it will make sense.QID = '$qNum' To match the two QID fields. as well as the original options for each questions (qA. you'll see that they are the field names from both tables.QID AND answers. $qB = $db_field['qB']. $answerB = $db_field['B'].QID = '$qNum' We're saying "Only bring back the records where the two QID fields match AND where the QID value in the answers table is equal to the value in the variable called $qNum". answers But we need a WHERE part.Home and Learn $result = mysql_query($SQL). we've typed the QID field. After the dot. But we only need the records where the QID field matches the qNum that was handed over from the previous page: AND answers. All of these values are then placed into variables.QID = answers. $question = $db_field['Question'].QID = answers. $qC = $db_field['qC']. A bit more complex. We're getting the value for the Question.

like this: print $question. $imgWidthB = '0'. $imgWidthC = '0'. like the one below: This is what you'll see when you click the button to View the Results. $percentA = '0'. $imgTagC = ''. print $answerC. $percentC = '0'. print $answerB. But that's not very interesting for the viewer.Beginners PHP We could just print the values to the page. $imgHeight = '10'. Better is some form of graphic. $imgWidthA = '0'. $percentB = '0'. –221– . Display a graphic for the results At the top of the code. print $answerA. $totalP = ''. Here's how it works. you'll notice some variables are set up: $imgTagA = ''. $imgTagB = ''.

If. $imgWidthC = $percentC * 2. Finally. you can multiply by. Which is what the following code does: $totalP = $answerA + $answerB + $answerC.jpg' HEIGHT = '10' WIDTH = '100'> The part we want to manipulate with our PHP code is the WIDTH value. $percentC = floor($percentC). and ordinarily would look something line this: <IMG SRC = 'red. $percentA = (($answerA * 100) / $totalP). one for each of the columns. This tag is used to display an image. the columns for A. First you need to total up how many people voted: $totalP = $answerA + $answerB + $answerC. for example. B and C hold how many people voted for a particular option. B and C by 100 and then divide by the total: $percentA = (($answerA * 100) / $totalP). In the answers table. We have three separate IMG tags in our code. 45 pixels is not very wide. 2 to give the red line some extra width: –222– .567. you can multiply A. Instead of setting it to a fixed value.Home and Learn What we're going to do here is to manipulate the HTML IMG tag. A held a value of 45 (meaning 45 people voted for this option). $percentC = (($answerC * 100) / $totalP). $percentB = (($answerB * 100) / $totalP). $imgWidthA = $percentA * 2. Next. Except. $imgWidthB = $percentB * 2. we can make the WIDTH of the red line image 45 pixels. we can use the inbuilt Math function floor to strip the "point something" at the end: $percentA = floor($percentA). we can set it to a value from the answers table. $percentA = floor($percentA). say. $percentB = floor($percentB). Much better to turn them all in to percentages. Because this would give an answer like 24.

$imgHeight . $imgWidthA . we'll take a look at how to build your own online Forum.jpg' Height = " . A percent sign and the option itself complete the line. followed by the percentage of people who voted for this option. $qA . $percentA . " " . $imgWidthB and $imgWidthC can then be used to build an IMG tag: $imgTagA = "<IMG SRC = 'red. Feel free to adapt and amend the code you downloaded. ">". we use the following: print $imgTagA . "<BR>".Beginners PHP $imgWidthA = $percentA * 2. But don't forget to make a backup of the original files! Next. " WIDTH = " . And that completes the survey walkthrough. The values in $imgWidthA. So the red line gets displayed first. To display this on the page. "% " . –223– .

and get working straight away. There are plenty of techniques here that can be carried over into your own pages. There are plenty of exercises to complete along the way. Copy the entire forum folder to the www directory on your server. Before you start. and hopefully you'll acquire some new coding skills. All the files for this section can be found in the forum folder you downloaded at the start of the book. You may not want a Forum on your site.Home and Learn How to Build an Online Forum In this section. of course. You should then have the forum folder inside of your www folder: If you double click the forum folder. That way. however. but the project is well worth doing all the same. so it's not all theory! This Forum. is not intended to be an application that you can simply upload to your own site. you won't be changing any of the original files. you'll see all the files and scripts mentioned in this walkthrough. The database for this walkthrough can be found in the –224– . it's a good idea to make a copy of this folder. you'll see what is involved in building a bigger web application. It is purely for teaching purposes. as we take you through the coding for an online Forum.

php Or you can try this: localhost/forum/forumTest.php What you should see is this very basic forum: –225– . Copy this folder the data folder of MySQL: To check if everything is working.0.0.Beginners PHP databases folder.1/forum/forumTest. and is called dbforum. This folder contains the database for this projects. start your server and navigate to this address: 127. and all the tables.

You'll see where you can adapt the HTML. You'll then see this: –226– . so click this link.Home and Learn Obviously. But the basics of the forum in the image above are common to most forums: you have the forum sections as hyperlinks. and then additional information along side each link. the HTML needs improving! But this is one of things you'll be changing. Only the Microsoft Word section is working. In our forum. Once you have loaded the forum into your browser. and how to add your own code. play around with the it. and how many people have replied to each post. we'll see how to get the number of posts in a section. as we go along.

Click this link.Beginners PHP What you're looking at is all the posts in the Microsoft Word section of the forum. Only members are allowed to Post on the forum. and you'll see the member name in the first column (Posted By). Only one Post has any replies – the first one at the bottom. and you'll see a new screen: –227– .

Home and Learn Because there are 11 replies.0. They only consisted of one or two tables. Try this for yourself. if you have Easy PHP version 1.0. You'll be taken to an area that asks you to enter a username and password. and Reply to them. we'll need a more complex database. Now that you have a good idea of how the forum works.8. allowing you to reply to this Post.1/home/mysql/ This will open the phpMyAdmin page. they are split over 2 pages. There's one important thing we need to do first: set up the database. For this test forum.0. Click on the link that says "Login Here".0. and you'll be allowed to Post topics in the Microsoft Word section. and there wasn't much linking done between each table. with a link to each page. For this project. you can use any of the following logins: Username administrator newBoyJoined member5 thisGirl thatGirl Password admin101 newboy member5 thisGirl thatGirl Login with one of the above.0. enter this address in your browser. you should see it on the list: –228– . http://127. Setting up a Database for a bigger project So far. If you have copied the dbforum database over to the data folder correctly. On the left hand side. the databases you have been constructing have been fairly simple. If you were logged in as a member. type this: http://127. click the drop down list for Databases. it time to get started. And lots of tables! To see what the database looks like.1/mysql/ If you have Easy PHP version 2. you'd see a different link at the bottom of the page.

For example. But this would mean that the one table would be holding a lot of information: the text for the post. and the text for the replies. In this database. we could have had one table to hold all the information about the Microsoft Word section. rather than lumping all the information into one or two tables. We could have had columns for the Posts. It's much better (for coding and for speed) to keep posts and replies in separate tables. –229– .Beginners PHP Select dbforum from the list and you should see the tables in the database displayed. there are a massive 12 tables! But why so many? The reason why there are so many tables is because we want to access the information in the database as quickly as possible. and columns for the replies. You can get a real speed boost by keeping data in different tables.

Home and Learn (When working on larger web projects. will pay dividends. taking the time to plan your database. or extra columns. One thing you don't want to do is get half way through your coding only to discover that your database isn't structured correctly. at the top. In phpMyAdmin. and all the tables you'll need. click on the forumsections table on the left hand side. You should see this: The two columns are sectionID.) As well as 10 tables for the posts and replies there is a separate table for the forum sections. Let's take a look at the Forum Sections table first: The Forum Sections Table The Forum Sections table is the simplest table in the database. Then click on Browse. and sections. and that you're going to need another table. and a separate table for member information. It consists of only two fields. If you look at the main page of the forum again. you'll see both the sectionID and the sections text in the status bar at the bottom of the page: –230– .

refresh your page. as in the image below: So the sections text in the Forum Sections table is used for the hyperlink on the main page of the forum. You'll see how that works soon. The sections text is the text for the hyperlink itself. From the page that appears. change Microsoft Word into anything you like. But have a look at the members table now. Now. click the Edit button (the pencil) next to secWP. Click the "Go" button. Exercise In phpMyAdmin. What happens? You should see the text on the page change.Beginners PHP The sectionID is at the end of the link: sID = secWP. with Forum start page displayed in your browser. –231– . The sectionID is used to identify which section of the forum a visitor wants to go to.

But you saw how to do this in an earlier section. Click the members table in phpMyAdmin. Because they'll give up their spare time.Home and Learn The Members Table The members table. But this would be a really bad way to construct a database. With a single members table. password. In the members table. should be encrypted. you can add even more fields to the members section. What about adding an Avatar field? This could be a link to an small image that the member wanted to use in their Posts and Replies. Just link to the members table. however.) The unique column (the primary key) is memberID. say as a moderator. (The passwords. say. you can add a Status field. This would allow you to change what a member is allowed to do. You should see the columns in the table: There are five columns in the members table: memberID. and email. then click Browse at the top. You'll see this column in the other tables. But the members table we have here is really basic. signupDate. username. Its these members who keep a Forum alive. you don't need to add username fields into every post and reply table. and a reference field in other tables. When you're displaying information about a Post or a Reply. If you match the memberID in. The alternative is to include a username column in the posts and replies table. by the way. it's a good idea to give them a little control over the Forum. holds information about people who have joined the forum. the wpposts table with the memberID in the members table. Depending on what type of forum you want. we haven't done this. For tutorial purposes. then. as its name suggests. as well. But we're sure that you can think of more fields that can be added to our basic members table! –232– . you'll want to include which member did the posting or replying. You could add more fields. because you'd be duplicating information. you then have an easy and efficient way to display the member information. A common practice in Forums is to reward loyal members who Post and Reply often with a higher status than other members.

and datePosted.the text for the Post . Click on this table in phpMyAdmin. Here's what they all do: threadID memberID threadTopic postText datePosted .All posts to do with PHP Since all of these tables have the same structure.NET . You should see the following: There are five fields in each of the post tables: threadID. we'll just take a look at the wpposts table.All posts to do with Visual Basic .the date the memebr Posted the topic We'll access these post tables when a user clicks on a particular forum section on the main page. you'll see this in the status bar: –233– .All posts to do with Microsoft Word .All posts to do with Microsoft Excel . threadTopic. and what they are for: wpposts vbposts xlpostswdposts phposts . Here's what each Post table is called. When they do. then click the Browse button. postText.the text used in the hyperlink when viewing the topics page . memberID. this is what the user sees in the browser: If you hold your mouse over a link.All posts to do with Web Design .used to identify an individual post (the primary key) .used to identify which member posted this topic .Beginners PHP The Post Tables There are 5 Post tables in the database. one for each section of the forum.

NET section . Then click the Browse link at the top of the page. When the link is clicked.All replies for the Microsoft Word section . You should see the following: –234– . We'll only be displaying records where the threadID fields match.All replies for the Microsoft Visual Basic . Hold your mouse over a different link and you'll see the pos1 change. and is the threadID field. The pos1 is coming from the table. and a short description: wpreplies xlreplies phreplies vbreplies wdreplies .Home and Learn The thing to notice about the link is rID=pos1.All replies for the Microsoft Excel section . Here's the table names. all these tables have the same structure.All replies for the Microsoft PHP section . we'll be pulling information from the reply table. The Reply Tables There are 5 Reply tables in the database. In phpMyAdmin.All replies for the Microsoft Web Design section Again. click the wpreplies table on the left hand side. one for each section of the forum. So we'll just examine the wpreplies table. The reply table will also have a threadID field. The final five tables are for the replies.

used to identify which member replied to a post .Beginners PHP There are five fields in this table: ID. Here’s what they do: ID threadID memberID reply dateReplied . But if other posts have replies they would be labelled pos2. When you construct your own –235– . threadID. You can then say.the primary Key.the date the meber replied to the post At the moment." The memberID field is also present in this table. To get a clearer idea of how this database is structured. study the following list: Table Name forumsections members wpposts wpreplies sectionID memberID threadID ID sections username memberID threadID Field Names password threadTopic memberID signupDate postText reply email dateReplied These are the tables we'll be working with. "Select all the replies where there is a threadID match. and dateReplied. etc. the only Post to have any replies is pos1. The memberID is in three of the four tables above. An auto incrementing number.used to identify which post a member is replying to . memberID. reply.the text of the reply . pos3. We'll be using these fields to link information. the threadID is in two of the tables. That's why there are no other values in this field. The threadID of the wpposts table is linked to the threadID of the wpreplies table. This allows us to link to the members table and display the username of the member who replied. . when we do our coding.

Planning like this can speed things up when you're pulling data from your databases with PHP code. we can take a look at the code. –236– . Now that you have a decent grasp of just how the database is constructed. it's important to consider which fields you can use to link information in different tables.Home and Learn databases.

But we want to take some information to this page (which forum the user asked for).php is loaded. we'll take a look at the main page of the forum – forumTest. After an equals sign ( = ) you type what is going into the variable name (secWP. when you hold your mouse over it: pageThread.1/forum/forumTest.php.php?sID=secWP The page the user will be taken to is called pageThread. This. Here's what we'll be doing: €¥A user clicks on a link on a forum page €¦The hyperlink will contain a variable that we can use to access our database tables €§Take this code and pull records from the table As an example. You saw that the hyperlink in the status bar is this. then. There's a good chance you'll need to do this in your own projects.0.php.php page Load up the forumTest.php page in your browser by typing the following address: 127. Off we go then! The forumTest. in the hyperlink above). This is done by adding a question mark after pageThread.0. for us). we can grab that sID variable and do something with it.php –237– .Beginners PHP The PHP code for the Forum There are a lot more PHP pages for this project than there were for the other projects you tackled. is the strategy we'll use for most of the forum – pass variables to other pages by using GET data. take the Microsoft Word Forum. and is widely used on the internet. so it's well worth learning. To begin the forum walkthrough. or set up some session variables. But the strategy that is used for this project is more or less the same for all pages. When pageThread. The question mark tells PHP that there is some GET data to follow. You then type a variable name (sID. We need to do this because there is no easy way to hand variable information from one page to the next.php. You could write a cookie. But the technique we're using is a common one.

of course. not something you'd want on your own site – that table looks far too basic! But the code is what we're interested in.1/forum/forumTest.0. Here's the coding strategy: €¨Get the number of posts in each forum €©Get the number of replies for each post €ªGet the Forum main topics €«Build up some hyperlinks –238– .Home and Learn You should see the main page of the forum.php Or localhost/forum/forumTest.php The HTML is. This one: The address to type in your browser is: 127.0.

But the SQL is not too difficult. because we only need a limited amount of information: how many forum sections there are. –239– . you can make a start right away in changing this! Exercise Even if your table HTML skills are a bit patchy. On line 7 of the code. it looks rather long and daunting. Again. change the bgcolor to anything you like. and see what happens: #F84EFC #402C3E #74283E What happened with the darker colours? Try a few colours of your own. Try these. and a count of how many replies there are in each forum section. open up the code for the forumTest. The first eight lines of the code are just variables to hold the table HTML. the posts are in the table called wpposts. a count of how many posts there are in each forum section. In fact. you'll see this: $tableHeaders = "<TR WIDTH = 200 height = 10 align = center valign = middle bgcolor =#00EBEB>" Change the bgcolor to anything you like. You'll see some comments in the code. The cell colouring is done with this line: $tdStart = "<TD WIDTH = 200 height = 100 align = center valign = middle bgcolor =#F84EFC>".php page. Start with the same colours as above. At first sight. Bearing this in mind. and the replies are in the table called wpreplies. and what the link text should be. This sets the look and feel of the forum. and see how you get on Another thing you can change is the main cell colour. The Forum main topics are in the table called forumsections. so as to break it down into manageable chunks. you can still change the colour scheme.Beginners PHP €¬Print out a HTML table The problem here is that we need to gain access to more than one table in our database.

Home and Learn Suppose you decided to go for one of the darker colours for the heading. for example. we set up some HTML for the hyperlinks: $hrefStart = "<A HREF = pageThread. the HTML would be this: <FONT COLOR = white>White Text</FONT> Where in the PHP would you put the FONT tag? Exercise Using the colours above. –240– .php?sID". change your table so that it looks like this one: Ok. After the table HTML. let's move on and examine the code. How would you change the font colour for the heading text? Can you see what you would need to change? If you wanted white text.

etc The technique we'll use is to loop round these tables. The first code inside of the if statement is a for loop. We'll put something into the sID variable later. If you hold your mouse over each link. and the part after php. The for loop starts like this: –241– .php. We want to record how many posts there are in each forum section. $numPosts[] = array(). secVB. so we won't go into it. for example. The page we want to take the user to is pageThread. An if statement comes next. The next 15 lines in the code set up some arrays. secWD. It will be one of five values: secWP. Print a simple "database not found" statement. you'll see this sID variable change. secXL. You'll see what they all do as we go along.php. $tblReply[] = array(). to see if a connection to the database has been found: if ($db_found) { } You can add an else part to this. The next six lines just get a connection to the database. and the names of the tables for the replies: $tblPosts[] = "wpposts". The important part here is the page we want to take the user to when a link is clicked. We want five arrays.Beginners PHP $hrefEnd = "</A>". etc $tblReply[] = "wpreplies". This will be the GET data that we want hand to the page called pageThread. They are: $secIDs[] = array(). $tblPosts[] = array(). and a variable name.php. and secPH. if you like. This should say what to do if the database is not found. $numReply[] = array(). as well: ?sID. It's these values that we want to hand over to pageThread. We've set these arrays up to hold the names of the tables for the posts. You've met this code before. so we need to loop round each table and count the number of rows in each post table. But we're adding a question mark. and get information from each table. But notice the two arrays called $tblPosts[ ] and $tblReply[ ].

the SQL variable will hold this: $SQL = "SELECT * FROM wpposts" The next time round the loop. You would then use this number in the for loop. the first line of the for loop is this: $SQL = "SELECT * FROM " . $numPosts[$i] = $num_rows. The code would break right here. we have this: $result = mysql_query($SQL). A better way to do this is use code to get how many rows there are in the forumsections table. and this is what the line does. We need some SQL to hand to PHP. If it is true. We're testing for this in the if statement. if ($result) { $num_rows = mysql_num_rows($result). the only thing that changes about the SQL is the name of the table. If any results are found then the variable called $result will be true. To count the number of rows in each table. $tblPosts[$i]. we've stuck to a hard-coded value. $i++) { } The value of 6 is a hard-coded one. We know there are only five main sections in our forum. though. For teaching purposes. and we won't be adding any more! To count how many rows there are in each of the post tables. $i < 6. Suppose you wanted to add more sections to the forum.Home and Learn for ($i = 1. The first value we stored in the $tblPosts array was "wpposts". } We pass the SQL to the inbuilt PHP function mysql_query( ). So the first time round the loop. But this is not a good idea. then next two lines will be executed: –242– . the SQL will be this: $SQL = "SELECT * FROM wdposts" Each time round the loop.

just like we did with the other two loops): while ($db_field = mysql_fetch_assoc($result)) { } The variable $db_field will hold the array data that is brought back from mysql_fetch_assoc($result). and then execute that against the database. $hrefEnd. a while loop this time. and build up the links. while ($db_field = mysql_fetch_assoc($result)) { $secIDs[$loopCount] = $hrefStart . (There are only two columns in this table. The third line sets up a loop counter. Then we have the while loop (actually.$numPosts. } The first two lines set up some SQL. We want to record how many replies there are in each forum section. $result = mysql_query($SQL).) The function will bring back data in this format: –243– . we'll use this array to print out how many posts there are in each forum section. $numPosts[$i] = $num_rows. $loopCount = 1. The next few lines of the code are for the replies.Beginners PHP $num_rows = mysql_num_rows($result). ">" . returns an array. "=" . $loopCount++. This inbuilt PHP function. We want to get the forum main topics. $db_field['sections'] . $db_field['sectionID'] . if you remember. Here's the code: $SQL = "SELECT * FROM forumsections". The first one just returns how many rows there are in a table. When the loop is finished. we should be testing to see if $result is true. When we come to write our HTML for the hyperlinks. We do this in exactly the same was as for the posts – just loop round the $tblReply array and execute some SQL. The next part of the code is a little bit trickier. The array that is brought back is a row from our forumsections table. The second line puts the number of rows into the array we set up earlier . We're doing both of those things inside of another loop. We use this to access a different slot in the $secIDs array. the number of replies in each section is held in the array called $numReply: $numReply[$i] = $num_rows.

–244– . The text for the link is then this: $db_field['sections'] Finally. we add the rest of the HTML code for a hyperlink: $hrefEnd The last thing we do in the while loop is to increment the loop counter: $loopCount++. We want to store the hyperlinks in this array. The part before the equals sign is this: $secIDs[$loopCount] $secIDs is the name of one of the arrays we set up at the top of the page. "=" . $db_field['sections'] . The hyperlink in $hrefStart was this: $hrefStart = "<A HREF = pageThread. $db_field['sectionID'] After this code executes.php?sID". it would give you something like this: pageThread. ">" . $hrefEnd. $db_field['sectionID'] . We're adding the sectionID after ?sID in the hyperlink above: $hrefStart .Home and Learn Column_Name => Data To access the data in the array. The right pointy arrow ( > ) completes the first part of the "A Href" HTML code. It's a long line that spills over into two on these pages: $secIDs[$loopCount] = $hrefStart . $db_field['sections'] . "=" .php?sID=secWP To add the text for the hyperlink. That's what the first line of the while loop does. $hrefEnd. we also have this in the while loop: ">" . you can then do this: $data = $db_field[Column_Name].

$tdEnd. $secIDs[$i] . print $tdStart . What the loop does is to print out table code. It prints out the row start tag (<TR>). print "</CENTER>". The first line just prints out the HTML code to centre things (note the American spelling). we have a for loop. print $TableStart. print $tdStart . The last line in the for loop prints out the row end tag (</TR>). and you'll get there. $numReply[$i] .php. and then some table data tags (<TD>). and prints out the formatted headings we set up (these include the colour changes you made earlier). This prints out the HTML for the start of a table. print $tableHeaders. $i < 6. Here's a summary of what we did: €-Set up some variables to hold HTML table information –245– .php code is to print out the HTML table. for ($i = 1. And that completes the code for the main page of our forum. we print out the HTML for table end. Next. it's quite difficult. After the loop has finished. forumTest. print $tdStart .php?sID=secWP>Link Text</A> The last thing we do in the forumTest.Beginners PHP And that's the while loop! Yes. But study it for a while. Here it is: print "<CENTER>". $tdEnd. $tdEnd. Remember: all we want to do is to build up an array of hyperlinks. Inside of each table data tag is the data from our three arrays $secIDs. $i++) { print $RowStart. and end the centre tag. $numPosts. Each hyperlink will be in this format: <A HREF = pageThread. and $numReply. } print $TableEnd. Then we have our two variables we set up at the top of the code. $numPosts[$i] . print $RowEnd.

php page When the user clicks on a forum section. The pageThread. the number of posts. You'll see this: –246– . The page looks like this: If you are logged in as a member. however. you'll won't see that text at the bottom. you can try to add that too. If you know any CSS. the hyperlinks. and built up a hyperlink €²Looped round and printed out the table.Home and Learn €®Set up some arrays to hold information from the database tables €¯Set up an array to hold all the hyperlinks €°Accessed the database. and returned the number of rows in the posts and replies tables €±Returned the information about each forum section. and see if you can improve things. Next.php.php page. and the numbers of replies Exercise Play around with the HTMl Table code. they are taken to the pageThread. we'll take a look at the code for that page printed out in all the hyperlinks: pageThread.

php page. the $nonMember variable will be blank. The alternative is to have an open forum where anyone can post and reply. but we thought we'd show you both techniques! Exercise Change the colours of the table headers for the Posts page. If it's blank. print the message. if it's not blank. After the session variable is checked. Here. The reason it's in a page of it's own is just to cut down on the amount of code in the pageThread.Beginners PHP Only members are allowed to post topics and reply to others. But this opens the forum to abuse. –247– . you'll see a variable near the top of the page called $nonMember. Open this page up. we have this line: include 'forumHTML. But if you open up the code for pageThread.php'. We could have done the same with the forumTest.php (in the forum folder). The login part of the forum is more or less the same one you met in the first walkthrough. and the colours for the cells in the table. an if statement will check what is inside of the $nonMember variable. If you're not logged in. As an exercise. we're including a file that holds all the HTML for the table. and a hyperlink. Then reload the page to see your new message. change this message to anything you like. especially from people who want to spam your forum with lots of hyperlinks advertising their own sites and wares. the following text is added to the variable: $nonMember = "YOU NEED TO BE LOGGED IN TO POST (MAKE SURE COOKIES ARE ENABLED IN YOUR BROWSER)". Change the text in the headers to any colour you like. Later in the code. print the link to post a topic. and you'll see the same table code you met in the main forum. If you are logged in as a member.php page.

we're checking to see if the page in the browser was loaded via a hyperlink click or a refresh (GET). } For the rest of the code. we need to do the following: €³Set up an array to hold all the posts €´Find out how many replies there are for each post €µFind out which member posted the thread €¶Print the table out –248– . if (isset($_GET['sID'])) { $secCode = $_GET['sID']. } } Here. The next line is an if statement: if ($secCode <> '') { } Here. If it is blank. then something went wrong. These are used to get some SQL. In which case. we're checking if the variable called $secCode is not blank. there will be some GET information stored that we can try to retrieve. If it was. So $secCode is either going to be blank. we have a function called getPostSQL( ) and one called getReplySQL( ). secVB. secXL. we have this: if ($_SERVER['REQUEST_METHOD'] == 'GET') { $secCode = ''.Home and Learn After the include file. the code at the bottom gets executed: else { print "Forum Not Available". secWD. or it will have one of our five values: secWP. and you'll see how they work soon. This starts off a being blank: $secCode = ''. we can return this into the variable called $secCode. We're setting up a variable called $secCode. But after the function. But if our variable from the previous page is set (the sID variable). Only if it's not blank will the code for the if statement be executed. or secPH.

php" . secXL. ">Create a new post</A>". if you open up the code for pageThread. breaking it down into manageable chunks. This is a call to one of our functions at the top of the page. the Excel section. –249– . $replyHTML = "<A HREF = postForm. The first four lines to examine are these (the third line spills over into two. If the member wants to create a new post. This will hold the information about each post. we have our first bit of code from our list: Set up an array to hold all the posts.php you'll see a lot of comments. After that. $replyHTML = "?sid=" . The result of the function will be returned to the same variable ($secCode = ). Set up an array to hold all the posts Inside of the $db_found if statement. etc? The only thing you need here is whatever is inside of the $secCode variable (secWP. though. $replyHTML . Was it the Word section. we have an if statement to check if the database was found. The fourth line just passes whatever is inside of the $secCode variable to a new variable called $forum. We're handing the function whatever is inside of the secCode variable (getPostSQL($secCode) ). $secCode. The first line is this: $secCode = getPostSQL($secCode). on these pages): $postData[] = array(). This is the same code as before. $forum = $secCode. The next six lines connect to the database. etc). the VB section.Beginners PHP €·Print out the "login" link. you need to pass in which forum section they want to add the post for. We set up an array called $postData[]. The next two lines set up the "Create a new post" hyperlink. or the "Non Member" information There's quite a lot to do! Again.

we can print out an error message. use ASC. We want a descending sort. secWD. we check how many rows were returned: if ($totalRows <> 0) { } elseif ($totalRows == 0) { print "This Forum is not yet available". After setting a rows counter to zero. secVB.Home and Learn If you study the function. Next. we hand it to PHP for processing: $result = mysql_query($secCode). the $result variable will be true. and reload it in your browser. we get the number of rows in a fourm section: $totalRows = 0. ++$i) { –250– . Is it secWP. so we've used DESC. you should be able to figure out what it does. Here. If you want an ascending sort. } If the total number of rows is not zero. But it's just a series of if statements that check what is inside of $sectionCode. But notice the ORDER BY clause at the end. After we grab the SQL. secXL or secPH? Whichever one it is. Exercise Change DESC to ASC. some SQL gets returned: $sql = "SELECT * FROM wpposts ORDER BY datePosted DESC". then the main code is executed. It sorts results based on a table column that you provide. $totalRows = mysql_num_rows($result). If no rows were returned. we want to sort the results based on the datePosted column. The first thing to get executed inside of the new if statement is a for loop: for ($i = 0. Save the page. This is another SQL command you can use. The only thing that changes is which table we want to pull data from. Watch what happens. $i < $totalRows. If any results are returned.

and position 2 holds a value of 30. "Clip Art". } What we're doing here is looping round each row in a database table. each position in the array will hold more than one value. So position 0 in the array above holds a value of 10. you can do it like this: –251– . Like this: $My_Array[] = array(). (You can also have a 3D array. "mem1". Each row will be like this: Column Name threadID memberID threadTopic postText datePosted Value pos3 mem1 Clip Art Got some good clip art? 2006-04-13 12:11:06 In the post tables. But for us. You can store all of this information into an array of your own. we're returning a row of data from our table. in the code above. and putting the results into an array called $postData. When we use mysql_fetch_array( ) it will fetch back each column name. position 1 holds a value of 20. It will hold a row of data from the database table. "Got some good clip art?".) If you want to just access the datePosted value. "2006-04-13 12:11:06" So position 0 now holds more than one value. But now. $My_Array[1] = 20. The new array will be like this: $My_Array[0] = "pos3". each position can hold only one value. 2D Arrays In a normal array. $My_Array[0] = 10. $My_Array[2] = 30. It holds 5 values. but this is far more complex than we need. This is a 2D array – an array where each postion holds more than one value. and it's value. Here’s how they work. there are 5 columns. But this is a new type of array – something called a 2D array.Beginners PHP $postData[$i] = mysql_fetch_array($result).

followed by square brackets. you type a column name (or key value). reload the page. Exercise Add this new for loop to your code: print $postData[0]['threadTopic'] . Refresh your page and see what happens. } print $postData[0]['threadTopic'] . refresh the page. Save your work. "<BR>". Now change the 0 to 1. If all that is a bit confusing. you need a postion in the array. $i < $totalRows. Now change the 0 to 1. save your work. and refresh the page. In the line above. Now change 'threadTopic' to 'datePosted'. $i < $totalRows. "<BR>". } print $postData[0]['newValue'] . Simply type a new name in between the square brackets. for ($i = 0. and its value. You can also add new keys and values to a 2D array. try this exercise. Exercise Add the following to the end of your for loop (the last line): for ($i = 0. "<BR>". To access just a particular value in that postion.Home and Learn $postData[0]['datePosted'] So the name of you 2D array goes first. Like this: $postData[0]['newValue'] = "new value here". In between the square brackets. ++$i) { $postData[$i] = mysql_fetch_array($result). save your work. Again. we've specified the datePosted column. and refresh the page. ++$i) { $postData[$i]['newValue'] = $i. Try the other Column Names from the table above. and watch what happens. What did you notice? –252– .

Each column in the spreadsheet represents a value for each postion. the postText and the datePosted. } –253– . The code that does that is as follows: $cnt = count($postData). ++$i) { $rep = $postData[$i]['threadID']. Find out how many replies there are for each post We've just used a 2D array to store the row information from our database table. The next thing to do is find out how many replies there are for each post. $rep). Each row in the spreadsheet represents a postion in the 2D array. $numRows = mysql_num_rows($result). for ($i = 0. the memberID.Beginners PHP In summary: use a 2D array when you want each position in your array to hold more than one value. $i < $cnt. Each postion in the 2D array will hold the threadID. If you're still having problems grasping the concept of 2D arrays then think of them like an Excel spreadsheet. $postData[$i]['numRows'] = $numRows. A normal array would look like this: And a 2D array would look like this: Back to the forum code (delete any code you added for the exercises above). $result = mysql_query($repSQL). the threadTopic. $repSQL = getReplySQL($forum.

threadID = '$reply'". The second function has two arguments. etc. we make a call the other function at the top of the code: $repSQL = getReplySQL($forum. $i < $cnt. This is so that we can loop through each postion. a section code ID (now stored in the ($forum variable). This number is then stored into the variable called $numRows. We're saying. we get a count of the number of positions in the 2D array. The value for this key is whatever is inside of the variable called $numRows. –254– . $rep). This is what allows us to link both tables in the above SQL. Because of the way we set up our database. After the SQL executes. we have a threadID field in both the replies and post tables. ++$i) { $memb = $postData[$i]['memberID']. pos2. Select all the records from the wpreplies table where there is a match on the threadID". po3. Depending on which forum section ID is being passed over. $memSQL = "SELECT * from members WHERE memberID = '$memb'". Here's we're adding a new key and a new value to our 2D array. it will return the number of rows where the two threadID's are the same. Next. We're using the variable $i to access each postion in the array. This returns the threadID from each position. and is called numRows. The value in $reply is coming from our 2D array. The first line in the for loop is this: $rep = $postData[$i]['threadID']. The final line of the for loop is this: $postData[$i]['numRows'] = $numRows. Find out which member posted The next thing we need to do is find out which member posted the original thread. The function is again a series of if statement. and the threadID from the array. a SQL statement is returned.Home and Learn First. Look at the SQL. This allows us to store a record of how many replies there are in each posts. This is from the Posts table. The key is between the second set of square brackets. The code that does this is as follows: for ($i = 0. and will be something like pos1. though: "SELECT * from wpreplies WHERE wpreplies.

as well. Again. The next line is this: $memSQL = "SELECT * from members WHERE memberID = '$memb'". We're looping round each position in the 2D array and grabbing the memberID. we run the SQL: $result2 = mysql_query($memSQL).) The first line inside of the if statement is this: –255– . } First. We're setting up some SQL here. the next few lines are executed. one of the values that was returned from the table was the memberID. If it is. $memName = $db_field['username']. we have an if statement testing to see if the variable called $result2 is true. we can select all the records where the memberIDs match. this shows you the benefits of planning your database before you start! The next few lines are these: $result2 = mysql_query($memSQL). $postData[$i]['member'] = $memName.Beginners PHP $result2 = mysql_query($memSQL). (We should really have an else part here. The line that does that is this: $memb = $postData[$i]['memberID']. if ($result2) { $db_field = mysql_fetch_assoc($result2). When we set up the 2D arrray. } } The for loop uses the same variable that we set up to count the number of positions in the 2D array. $postData[$i]['member'] = $memName. This should say what happens if $result2 is false. Because we set up our database with a memberID in three of the tables. Next. We're storing this in a variable called $memb. if ($result2) { $db_field = mysql_fetch_assoc($result2). $memName = $db_field['username'].

So the line is this: $memName = $db_field['username']. $postData[$i]['emailAddress'] = $email. We print out the TD start tag. The only thing we need is the username. The key is member. This is then added to the 2D array: $postData[$i]['member'] = $memName. just refer to its position in the array. grab the column name from the table. Get the email address. and add a new key to the 2D array. We're placing the username in a variable called $memName. or that Avatar we didn't set up! You'd do it like this: $email = $db_field['username']. In other words. we have this: $postData[$i]['member'] To print out a value from the 2D array. Here's just one line from the loop: print $tdStart . and the TD end tag. Print the table out The next thing to do is to print out all the information we stored in our 2D array. If you wanted to display other information about the member. We now have a new key and value in our 2D array – member.Home and Learn $db_field = mysql_fetch_assoc($result2). The technique is the same as the one in for the forumTest. In between that.php page . you would do it here. The position is coming from the loop ($i). The array will return all the columns and the data from the table row. –256– . We're printing it out in a table. This holds the member's username. $tdEnd. for example. $postData[$i]['member'] . This is then placed into the variable called $db_field. and the key you want to print.just print out your HTML table headers. and loop round for the table rows and table data tags. This brings back the result as an array.

$forum . "</P>". ">" . print "<P align = center>" . page 4. $replyHTML .php>Login Here</A>" . If you hold your mouse over a hyperlink on the pageThread. etc. $hrefStart . "</P>". You'll see how they work in the next section. If $nonMember is blank. "&pageID=0" .Beginners PHP Examine the rest of the for loop that prints out the table. "<A HREF = login. then we can print out the hyperlink to allow the member to post a new topic. then we can display some HTML asking the user –257– . } This just tests what is inside of the variable we set up at the top of the page. you'll see something like this: pageReply. page 3. If it's not blank. the whole line prints out the hyperlink.php page. $nonMember . We're passing a value of zero because this is the first page of the replies. The final part of the pageThread. and 0. "&forum=" . secWP. We're trying to pass the following three variables: rID forum pageID The values in the variables are 1. $tdEnd. "=" . An important part of the line above is this: "&pageID=0" As you may have realised.php code is this: if ($nonMember = = '') { print "<P align = center>" . } else { print "<P align = center>" .php. or page 2 of the replies (if there is a page 2). See if you can understand what's going on. Especially this rather long line (split into three lines on these pages): print $tdStart .php?rID=1&forum=secWP&pageID=0 This means that we are trying to pass three things to a page called pageReply. But the pageID is used to display the links that will take a user to say page 1 of the replies. $postData[$i]['threadTopic'] . "</P>". $postData[$i]['threadID'] . $hrefEnd .

You'll see how to do this in the next section. etc. That way a user can click onto page 2 of the posts. allowing us to set hyperlinks for each page €¼Display information about the original post €½Display which member posted €¾Find out which members replied €¿Display all the replies. you'd need to spread the posts over more than one page. Supppose your forum is really large. they will see this page: –258– . If so. There is however. You can also add a link to register. We did this in a previous section. But that's it! That's the code to display all the posts in your forum. which explains how to write the code for displaying the replies to a post – we'll definitely be needing that pageID! The pageReply.Home and Learn to login in. display a link so they can post a reply.php page is a little bit longer than the others. page 3. If so. This page has to do the following: €¸Check if the user is a member. but limit them to ten replies per page When a user clicks on a Post. €¹Set up some functions to handle the SQL €ºGET the post and the forum section that the user is replying to €»GET the pageID just in case there is more than 1 page of replies. if you like.php Code The code for the pageReply. so we won't cover it here. a problem.

we first set a variable called $secCode and a variable called $postID to blank strings. } } Here. $secCode = $_GET['forum']. if (isset($_GET['rID'])) { $postID = $_GET['rID']. and pageID variable: if ($_SERVER['REQUEST_METHOD'] == 'GET') { $secCode = ''. If so. This is the data in the rID variable. we can get the information that was handed by the previous pages: –259– . though. we're checking to see if the page was loaded using the GET method. we need to GET the data that was passed by the previous page. If it was. The code that checks if the user is a member or not is the same code for the previous section. $postID = ''. the forum variable. After the functions.Beginners PHP This is the page we're now going to examine. We then test to see if the rID variable has been set. $pageID = $_GET['pageID'].

10". we can limit the data we pull from the replies table. $result = mysql_query($repCode). ". allows you to limit the number of results that you pull from a table. "'" . $repCode = $repCode . $pageID . build up some HTML for the reply link. as its name suggests. if we're not going to be displaying all of them. $postID . we first need to find out how many people relied to a Post: $repCode = getReplySQL($secCode). After all. " LIMIT " . This gets some SQL that we can use against the reply tables. and open a connection to the database. there's no sense in getting all the replies. $totalRows = mysql_num_rows($result). If the database is found. we'll have all the replies for a particular post. $postID . The forth line tells us how many replies there are in total.Home and Learn $postID = $_GET['rID']. The SQL command LIMIT. $pageID = $_GET['pageID']. "'" . To limit the number of replies. $pageID . "'" . When the SLQ is executed on the third line. we have this: $repCode = getReplySQL($secCode). $repCode = $repCode . $postID . If the $totalRows is not zero. "'" The rest of the line is where we're limiting the results: LIMIT " . ". We're putting this into a variable called $totalRows. $secCode = $_GET['forum']. The first part of the second line just adds the $postID to the SQL: $repCode = $repCode . then we can get some more SQL. This returns some SQL. Since we're only going to be displaying ten links per pages. we make a call to one of the functions at the top of the page. you've already met in the previous section: Test to see if secCode is blank. Take this SQL as an example: –260– . The first line again makes a call to the functions at the top of the page. 10". "'" . First. The second line adds the postID to the SQL. The second line is where we're building up some SQL to limit the number of replies that will be pulled from the table. "'". The code after that.

11 divided by 10. if ($result) { for ($i = 0. We use the floor( ) function to get rid of any "point something" at the end. $i < $numRows. and 1 on the third. ++$i) { $replyData[$i] = mysql_fetch_array($result). The first line just counts how many replies are in the array. It started off as zero. The next line divides the number of rows by 10. so floor( ) will strip this off. we'd need three links – 10 on the first 2 pages. We pass this to a variable called $cnt for use later in the code.1. we're putting each row from the table into an array called $replyData. If there are 11 replies to a post. You can then add it to the hyperlinks. In our code. $numRows = mysql_num_rows($result). This is passed to the code when a hyperlink is clicked. would give us 1. for example. If we had 21 replies. and put the data from the table into an array: $result = mysql_query($repCode). We don't need the . Clicking the second link will take you to the second page of replies. then we need to change the value in the variable called $pageID. The next bit of code gets information about the thread: $result = mysql_query($posCode). as you'll see. If we wanted to start pulling data from row number 11. But we also need to find out how many links are needed. } } Notice how the loop goes from 0 to $numRows. The number zero means start pulling data from the first record in the table. because this will be the first page of results. The second number says how many records you want to grab. $linkNum = floor($totalRows / 10). This values gets changed later. Inside of the loop. the start value is coming from the variable called $pageID.Beginners PHP SELECT * FROM tblReply LIMIT 0 10 The first number after LIMIT is which record from the table you want to start at. We can then execute the SQL. as we do if there is more than 10 replies. we need 2 links. $numRows = mysql_num_rows($result).1 at the end. if you remember. –261– . The code that counts how many links are needed is this: $cnt = count($replyData).

To find out which members replied to the post. To find out which member posted the thread. We can then use these variables later in the code. $datePosted = $db_field['datePosted']. if ($result) { $db_field = mysql_fetch_assoc($result). But we need to check if a row is returned. The variable $db_field will then hold the fields from the Posts table. $memPost = $db_field['memberID']. the posText. $datePosted = $db_field['datePosted']. we have this: $memSQL = "SELECT * from members WHERE memberID = '$memPost'". } We first execute the SQL we set up at the top of the code. } This is the same code you met in the previous section. $postText = $db_field['postText']. $postText = $db_field['postText']. $topic = $db_field['threadTopic'].Home and Learn if ($numRows = = 1) { $db_field = mysql_fetch_assoc($result). The next four lines return the threadTopic. This returns the original Post. ++$i) { –262– . If a row is returned then we fetch it back as an array: $db_field = mysql_fetch_assoc($result). $result = mysql_query($memSQL). we have this code: for ($i = 0. We use SQL to pull the record from the members table WHERE there is a match on the memberID fields. $memPost = $db_field['memberID']. and the memberID. the datePosted. This is then placed into a variable called $postName. These are all fields in the post tables. We then put theses into variables of their own: $topic = $db_field['threadTopic']. $i < $cnt. $postName = $db_field['username'].

$memSQL = "SELECT * from members WHERE memberID = '$memb'". As a reminder. $result2 = mysql_query($memSQL). } } What we're doing here is looping round the $replyData array. here's the links we want to print out: Hold your mouse over these links and you'll see this in the status bar: Or this. This is the array we set up earlier that holds information about the replies. We then execute some SQL on the members table WHERE there is a match on the memberID field. we add a new key to the $replyData array: $memName = $db_field['username'].Beginners PHP $memb = $replyData[$i]['memberID']. $memName = $db_field['username']. Once we find a match. We just want the memberID. $replyData[$i]['member'] = $memName. $replyData[$i]['member'] = $memName. so that users can go to other pages. if ($result2) { $db_field = mysql_fetch_assoc($result2). The next thing we do is to print the links out. for Page 1: –263– .

php?rID=" . $postID . print $linkPages . ">Page " . What we're doing here is looping round and creating links. The links are printed out with: print $linkPages . For page 2. "&forum=" . Here's the status bar (concentrate on everything after pageReply. If you click Page 1. Study the code and see if you can work out how it works. "&forum=" . $pageCount++. $linkCount = $linkCount + 10. $secCode. Compare the address in the status bar. You can then use this number to pull records number 11 onwards. " ".php): And here's the two lines in the code that builds the link: $linkPages = "<A HREF = pageReply. $secCode. $postID . } The variable $linkNum hold the number of pages that are needed. Here's the code that does that: $linkCount = 0. This is because you want to pull records 0 to 10 from the replies. But the two lines above this are where the hyperlinks get built. ++$i) { $linkPages = "<A HREF = pageReply. with the code in the loop. "&pageID=" . $linkPages = $linkPages . " ". pageID is zero. $pageCount .php?rID=" . $pageCount = 1. pageID is 10. $linkCount . $i <= $linkNum. for ($i = 0.Home and Learn The only thing to change here is the pageID. –264– . "</A>".

and for adding a new post to the forum. leads to a page called replyForm. when clicked on. be able to figure out what's going on. we can then print out the HTML table. you'll see this in the status bar at the bottom (you'll only see this link of you're logged in as a member): The code above for the $replyHTML variable is adding the following after the question mark: pid=pos1 sec = secWP When the link is clicked. $linkCount . You should. $postID . "</A>". we're passing these two variables to the page called replyForm. Again. by now. The pos1 is which post the member wants to reply to. We'll do that next. and the mouse held over the link. The Reply Form In the last section. $replyHTML = "<A HREF = replyForm. there was a variable called $replyHTML. ">Reply to this post</A>". When the link is displayed. $pageCount .php" .Beginners PHP $linkPages = $linkPages . The only thing that remains now is to look at the code for posting a reply. Finally. using all the information we have gathered so far.php.php. $replyHTML . "&sec=" . "&pageID=" . study the code. This is a hyperlink that. $secCode. ">Page " . while the –265– . But we're just looping round printing table data. Here's the code: $replyHTML = "?pid=" .

And the sec variable (the one that contained secWP) is handed to a variable called $secCode: $secCode = $_GET['sec']. When the button is clicked. All the PHP code does is to print out HTML for a FORM.php (in your forum folder). you'll see it's just a text area and a button.) The first bit of code is just the usual checks to see if the user accessing the page has logged in. if (isset($_GET['pid'])) { $postID = $_GET['pid']. from the previous page) is handed over to a variable called $postID: $postID = $_GET['pid']. When the member types the reply. if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) { header ("Location: login. open up the code for replyForm. } else { $memberid = $_SESSION['memID']. $secCode = $_GET['sec'].Home and Learn secWP is the forum section for Word Processing. } } So the pid variable (the one that contained "pos1". (If you display the page in a browser. and we'll see how it works. $postID = ''. and clicks the button. The member types the reply. } We also need to grab those variables from the previous page: if ($_SERVER['REQUEST_METHOD'] = = 'GET') { $secCode = ''. we'll use these values to update the database table. So. The ACTION attribue of the FORM tag is where the processing page is located: –266– . If they have. and put it in a variable: session_start(). we'll process the data on another php page. we grab the memberID. The form will contain a textarea and a button.php").

$hidMem = "<INPUT TYPE = Hidden Name = h3 VALUE =" . too. and h3. This is NOT how you'd want to do it in your own forum! There are security issues here. We're going to be using the POST method to hand over our values to a page called results.php page. The NAME of the textarea on the form is post.php. $postID . The next three lines just add some single quotes. $hidPost = "<INPUT TYPE = Hidden Name = h2 VALUE =" . we check to see if the form was submitted using the POST method: if ($_SERVER['REQUEST_METHOD'] = = 'POST') { } If this returns a value of true. After the function. because you're grabbing text from a textarea and trying to INSERT it into a database. Notice.php page. ">". $repText = $_POST['post']. Open up the code. When the button on the form is clicked. All we need to do here is to INSERT a reply to a post into the correct database table. The results. these hidden variables will get handed over to the page that processes the data – the results. $posID = $_POST['h2']. We'll be passing all these values to the processing page. We're grabbing all those HIDDEN values from the form (which had the NAMES h1. This takes one argument – the section code for the forum. Notice that the FORM also has hidden values: $hidSec = "<INPUT TYPE = Hidden Name = h1 VALUE =" .php'>". And there's our three variables: $secCode. and $memberid. We covered the security issues in an earlier section. then we grab that data from the form: $secID = $_POST['h1']. that the NAME attributes for these hidden variables are h1. and we'll take a look at it. The first thing to notice is the function at the top of the page – getReplySQL( ). $memID = $_POST['h3'].php page There's not too much code in the results. h2. and h3). $postID. h2. as well as the text in the textarea (which had the NAME post). ">". ">".Beginners PHP … METHOD ='POST' ACTION ='results. but try this exercise: –267– . $secCode . $memberid .

Home and Learn Exercise Login to the forum with one of the username/passwords you saw earlier (these are in the textfile called uandp. But surround the text with single quotes. You can check how long a string is with the strlen( ) function. You should see the message "No results".php. Type this: 'Some text here' Now click the button.net/manual/en/function.txt. This is because the code couldn't execute the SQL with those single quotes added. in your forum folder). Wasn't there something about magic quotes. A good run-down on how to use this can be found in the PHP manual here: http://uk.strlen. –268– . Reply to the post "A Brand New Forum". You'll see this basic form: If you just go ahead and click the button. the text Some text here should get added to the database. and strip slashes? How would you use these to lessen a SQL injection attack? Another secrurity issue to worry about is how much text to allow the user to type into the textarea. How would you solve this? Review the section on security.php A simple way to use this would be: $strCount = strlen($repText). especially the parts about SQL injection attacks.

The next code we have is some date code: $date_today = date("Y-m-d H:i:s"). We're also adding a time part that returns Hours. the posID will contain something like "pos1". etc). we've set the reply text field in the database tables to MEDIUMTEXT. } else { //Do the rest of the code here } This just prints an error message if the user types in more than 255 characters.Beginners PHP if ($strCount > 255) { print "too many characters in your reply". The $repText variable holds the reply the user typed in the textarea. $date_today . and the member ID is always "mem" plus a number (mem1. If you're restricting users to 255 characters. Minutes. The next line is a call to the function at the top of the page: $tableSQL = getReplySQL($secID). reply. $repText = $_POST['post']. then the day. then TINYTEXT would be a better option. memberID. The secID will contain something like "secWP". The function returns SQL to be used against the database table. dateReplied) VALUES ". The characters we're using between the round brackets of the date function mean we want the year first. then the month. $posID = $_POST['h2']. But it only returns part of the SQL we need: $sql = "INSERT INTO wpreplies (threadID. $memID = $_POST['h3']. me2. The second line adds single quotes to the date. so we can use it in the SQL. and Seconds. These will be separated with the "-" character. This can hold far more characters than 255. (However. "'".) But back to our (less than secure) code. We've just grabbed the data from the FORM and placed it into variables: $secID = $_POST['h1']. –269– . $date_today = "'" .

There is one useful database technique that may come in handy in your own code – how to deal with primary key fields that are not autoincrementing numbers." . $posID . The Post Form The form that the user fills in to post a new topic is this: –270– . The next line in our code adds the values. ". It already holds the first part of the SQL we need. "My Reply". But you should implement the error checking in your own code." . "(" . But we don't yet have the VALUES we need to insert into these fileds. we try to execute the query: $result = mysql_query($tableSQL). } And that's all we need to do on the this page: try to insert the reply into a reply table in the database. "2006-10-22 13:30:14")" After we open a connection to the database. Then we check to see if the SQL is executed successfully: if ($result) { print "Your Reply has been added to the Forum. We're now adding the VALUES. After the line is executed. memberID. and the commas. $date_today . "<BR>"." . Especially the checks to ward off attacks on your database! Posting a Topic on the Forum The final part of the walkthrough looks at how to allow users to post a new topic on the forum.Home and Learn In between the round brackets. Some of the error checking has been left out." . so as not to confuse the main techniques used. dateReplied) VALUES (pos1. the data from the variables. print "<A HREF = forumTest. we have the fields from the table. ")". mem1. $memID . "<BR>". We’re building up the $tableSQL string variable here. } else { print "no results" . reply.php>Back to the forum</A>" . It's a long line that spills over into two on these pages: $tableSQL = $tableSQL . We need the round brackets. Let's make a start. $repText . "<BR>". ". ". the string would be something like this: "INSERT INTO wpreplies (threadID.

">". except for the addition of a text box.Beginners PHP As you can see. If you open the page called postForm. $memberid . take a look at the resultsP. and the text area is called post. it's fairly basic. Again.php.php page (in your forum folder).php' The page we're posting the data to is called resultsP. ">". and the member id. $hidMem = "<INPUT TYPE = Hidden Name = h2 VALUE =" . and you can definitely improve on this! The form is similar to the Reply form.php. With this in mind. The text box on the form has been given the name tp. –271– . $secCode . And we're doing the same things in the code: hand over values to another php page for processing. you can examine the code for yourself. We want to hand over the forum section code (secWP). but notice the hidden variables: FILE REF $hidSec = "<INPUT TYPE = Hidden Name = h1 VALUE =" . We'll take a look at this code in a moment. we're using the POST method to post the form data to a php page: METHOD ='POST' ACTION ='resultsP.

the $posTopic variable will hold the heading for the topic. The problem is that the Primary Keys in the post tables are not auto-incrementing numbers. This is the same technique we used in the previous section: just put the POST data into variables. We'll take a look at these later. The $secID variable will hold something like secWP.php page At the top of the code. we have a field called threadID. How can you be sure that the database hasn't inserted your rows like this (and it will!): –272– . and the $posText variable will hold the text of the post itself. and the next row would be 4. etc. $posTopic = $_POST['tp']. we run in to our first problem. With an auto-incrementing number. The threadID field looks like this: threadID pos1 pos2 pos3 So you can't just add 1 to this field. But for the Primary Key in the post tables. as well) To get the data posted from the FORM. $memID = $_POST['h2']. But bear in mind what this page does – inserts the new post into the database table. the database would automatically add 1 to the ID field. we have this: $secID = $_POST['h1']. there's two functions. You don't have to do anything. There's another problem as well. (The security issues discussed in the previous section apply here. and the next new row will be pos5. After we get the connection to the database. if you insert a new row.Home and Learn The resultsP. Like this: ID 0 1 2 3 If you update the table. you can usually leave the database to update this field –all it needs to do is to add 1 to the previous value. the $memID variable will hold the member id. $posText = $_POST['post']. You have to make sure that the new row is pos4.

and just leave the number Sort the array with the lowest number first and the highest last Get the last value in the array (which will be the highest number) Add 1 to this number Put the "pos" part back Update the threadID array If you open up the code for the resultsP. 2. $numRows = mysql_num_rows($result). This is just a call to one of the functions at the top of the page. you'll have SQL like this: "SELECT * FROM wpposts". you'll see comments that tackle the items in list above. you'll get an error. 6. The next two lines are these: $result = mysql_query($SQL). A Primary Key field is one that has unique values. The first part of the code gets all the posts from the table: $SQL = getPostTable($secID).Beginners PHP threadID pos1 pos3 pos2 So the last row in the table is pos2. The second line returns how many rows we have returned from table. If you try to update this with pos3 as the new row. And that why you'd get an error. we need make sure that the new value in the threadID field is pos4. This selects all the records from a table called wpposts. We then set up an array to hold the threadID values: –273– . This is a common problem when you have your own format as the Primary Key in a database table – adding a new unique value when that value is not an autoincrementing number.php page. In the example above. 4. 5. Because there already is a pos3. When the function is run. This is a run-down on how we'll do it: 1. 7. 8. We'll need this for the for loop. The first line executes the SQL. 3. Get all the posts from the table Set up an array to hold the threadID data Strip the "pos" part.

fetches a row from a table. then. } The loop goes from zero. $posNums[$i] = ltrim($pID. 'pos'). but they are not sorted from lowest to highest. The first line in the for loop is this: $row = mysql_fetch_row($result). is placed into a variable called $pID. and get the threadID field: for ($i = 0.Home and Learn $posNums = array(). The next line does that: sort($posNums). you type the text you want trimming. To strip off the "pos" part of the threadID. you type the text you want examine. In between the round brackets. we can grab this value: $pID = $row[0]. Because we know that row[0] is our threadID field. –274– . $pID = $row[0]. The treadID . row[2] as the third. etc. 'pos'). as its name suggest. We're using the unbuilt function ltrim( ) to trim the "pos" part. The inbuilt function mysql_fetch_row. After a comma. $i < $numRows. we have this: $posNums[$i] = ltrim($pID. row[1] as the second column. we might end up with something like this: $posNums[] 1 3 2 So we have all the numbers in an array. to less than $numRows. We now need to loop round the rows in the table. $i++) { $row = mysql_fetch_row($result). It will fetch it back with row[0] as the first table column. After the loop finishes.

All that coding gets us the highest pos number from our threadID field. The end( ) function is used to move to the last element of an array. But we still need to add the VALUES. "200610-22 13:30:14") Once we have our SQL. ". we're putting the value returned by the function into a variable called $lastID. memberID. "This is the text". $memID . once we have the last number. Something like this: INSERT INTO wpposts(threadID. $lastID.Beginners PHP The inbuilt function sort( ) is used to sort the array. memberID. We can then go ahead an get the SQL for our INSERT statement: $tableSQL = getPostSQL($secID). datePosted) VALUES " We want to INSERT INTO the wpposts table a set of VALUES. datePosted) VALUES (pos1. we can add the "pos" back on: $threadid = 'pos' . Finally. ". This is done with the rather long next line: $tableSQL = $tableSQL ." . postText." . $date_today . We're just building up a string. The name of the array you want to sort goes between the round brackets of the function. threadTopic." . This calls the function at the top of the page. ")". ". we're using an unbuilt function. $threadid . we can get the last item in the array: $lastID = end($posNums). mem1. The function will return something like this: $sql = "INSERT INTO wpposts(threadID. The names of the table columns go between the round brackets. we can try to run it: –275– .$posText . "New Post". Again. ". $posTopic . increment it: $lastID++. "(" . threadTopic." . postText. Once we have the last number. But note that the square brackets of the array go missing. Here. Once the array is sorted.

Look at the code for replyForm.php>Back to the forum</A>" ." . Final Project There is no form for a new member to sign up to the forum. only with mem before the number instead of pos. } else { print "Couldn't add Post to the Forum". mem2. So here's a final Project for you to try. Add the SQL function. "<BR>". –276– . Write the code for this. just like we did above. and the rest of the code. The fields in the members table are: memberID username password signupDate email €ÄThe form will need to be posted somewhere. etc €ÂYou'll need to build up string for your INSERT INTO SQL €ÃUse PHP to create the Form. and one for the email address. mem3. €ÅYou need to bear in mind that the Primary Key in the members table is just like the threadID field. "<BR>".php and postForm. We can test to see if it is run successfully: if ($result) { print "Your Post has been added to the Forum.Home and Learn $result = mysql_query($tableSQL).php to see how to do this. } If the code executes successfully. And that completes the code for Posting new topics. print "<A HREF = forumTest. a new post will be added to the forum. and add links to the signup page in the rest of the forum. You can create a new php page for this. Here's a few things you'll need to bear in mind. In fact that completes our walkthrough of the entire forum! There is still work to be done. of course. You'll need to add textboxes for the username and password. €ÀThe Table is called members €ÁPrimary key is in the format mem1.

but the whole beginners PHP book. such as pageReply. any errors you need to correct in the forum? Most likely. you can always try to add some to the code.php. If you know any CSS. and not trying to overwrite an existing one €ÆTo add the links to the signup page. At the very least. We hope you enjoyed it. But that completes not only the forum. you'll always find a bug or three! And don’t forget to keep a copy of the origianl code.Beginners PHP You'll have to code for this. Speaking of the code. you'll need to amend the code in a f ew of the pages in the forum. and see what you can come up with. to make sure you're adding a new row. A simple hyperlink to your new signup page should do Play around with the rest of the forum. you should be able to improve the look and feel of the forum. In a larger web application like this. Good luck! –277– . and are motivated to take your new skills on to the next level.