PHP Mysql Project Book2
PHP Mysql Project Book2
http://xkcd.com/327/
Contents
About this guide ......................................................................................................................... 4
A quick word about software................................................................................................. 4
What is PHP? .............................................................................................................................. 5
How do I set up a server? .......................................................................................................... 6
Uh ohwhy isnt it working? ................................................................................................. 6
How do I write PHP programs? .................................................................................................. 7
Where do I put my programs? ............................................................................................... 7
How do I write a program? .................................................................................................... 8
What you should have understood so far ............................................................................. 8
PHP mixed with HTML ............................................................................................................... 9
Things to watch out for .......................................................................................................... 9
Concatenating variables....................................................................................................... 10
PHP and HTML exercise ....................................................................................................... 11
Basic PHP .................................................................................................................................. 12
Assignment....................................................................................................................... 12
Selection........................................................................................................................... 12
While loop ........................................................................................................................ 12
For loop ............................................................................................................................ 12
Do-while loop ................................................................................................................... 12
Operators ......................................................................................................................... 12
PHP exercises ....................................................................................................................... 13
User input................................................................................................................................. 14
Important parts to note ................................................................................................... 14
What happens when I press the button? ............................................................................ 14
Mini Project 1 Love Calculator .......................................................................................... 16
Input page index.php .................................................................................................... 16
Processing/output page calculate.php ......................................................................... 16
Sending information via the URL ......................................................................................... 17
Using $_GET data example .................................................................................................. 17
More PHP exercises ............................................................................................................. 19
PHP and MySQL Database Integration.................................................................................. 21
2
If you would like to get in touch, please find me on Twitter @codeboom or visit
http://codeboom.wordpress.com
Please feel free to copy, adapt and distribute as described under this Creative Commons
license http://creativecommons.org/licenses/by-nc-sa/3.0/
Notepad++ - free
PSPad free
Dreamweaver (code view) not free, and a bit overkill, but if you already own it then
great!
You will also need an internet browser. I realise that in most schools you dont have a choice
and you are probably stuck with Internet Explorer, but if your neighbourhood techies are
rather lovely its worth asking them to install Chrome just for the lovely JavaScript
debugging facilities.
What is PHP?
PHP is a scripting language primarily used to make interactive web pages. It is a server side
language which means it does its processing on a server, a bit like this:
User
I clicked a link to
page.php
Request sent to server
Server processes
PHP code
the HTML is
sent back to the
user
and produces a
HTML page
Sothe user only ever sees HTML pages. They cannot see the PHP code!
What is PHP good at?
1. Download either XAMPP (the full Monty) or XAMPP USB Lite if you want the small
version so that you can install it on a USB stick or other portable hard drive.
2. Open the installer and follow the instructions. It is best to install XAMPP in a
permanent location rather than on the desktop.
3. Once the installer has finished, find the xampp-control.exe (you might want to make
a shortcut to this) and run it. Click on Start next to the Apache and MySQL options
and make sure they go green and say Running. You can now close the window.
You should see the XAMPP test page if its working correctly, if not see the bottom of the
previous page for troubleshooting advice.
You might be wondering why we have called our page index.php ? Apache
(the web server) always looks for a page called index first this is the
home page of any site or app we may make. Other files can just be saved
as filename.php and will work just as well.
7
?>
Here is my program Im sure you can tell that the green part is a comment.
When you want to work on PHP code you need to start Apache/MySQL on the
XAMPP control panel
Save all of your PHP documents into the htdocs folder with the file extension .php
PHP files can be inside subfolders of htdocs
Run your PHP file by browsing to http://localhost/foldername
The default page (home page) of each folder is index.php
If you want to view a page with a different name, open
http://localhost/foldername/pagename.php
Final output is
only HTML code
You can easily tell which parts are HTML code and which are PHP code because PHP code
always has to be inside the PHP tags <?php and ?>
Correct
2. Sometimes you may want to put some HTML code inside a PHP section. This is fine,
but you must treat it as if it were just another string to be printed:
This will cause a syntax error because the
HTML code is inside a PHP section
Concatenating variables
You can concatenate variables into your output using the concatenation operator which is a
dot in PHP:
10
HTML
Is a ______________ language.
PHP
Is a ____________ language.
Mark-up
RAM
Variable
Internet
Browser
Score:
Statement
Scripting
Server
;
Code
<
Display
>
Database
Attribute
/ 12
11
Basic PHP
You will already be familiar with another programming language from your AS work. Here is
a quick reference of the basic statement syntax for PHP
Variable names in PHP have a dollar sign ($) in front of them, e.g.
Assignment
$name = Bob;
$age = 10;
The assignment operator is a single equals =
Selection
if ( condition ){
// statements here
}
elseif ( condition ) {
// statements here
}
else {
// statements here
}
While loop
while( condition ){
// statements here
}
For loop
Do-while
loop
Operators
do {
// statements
while ( condition );
The comparison operator is a double equals ==
Logical and operator is &&
Logical or operator is || (pipe is to the left of Z on a Windows keyboard)
The concatenation operator is a dot .
12
PHP exercises
Printing - HTML and PHP
1. Write the phrase Hello World as HTML, with a line break afterwards
2. Print the phrase Strawberry Jam using a php print statement
3. Make Hello World bold
4. Make Strawberry Jam bold
Variables
1. Make a variable called firstname and assign it the value of your own first name
2. Make a variable called age and assign it the value of your age
3. Make a variable called blueeyes and assign it to either true or false
Printing with variables
1. Print a line that says Hello <name>, nice to meet you! where <name> is the value
of your variable called firstname
2. On the next line, print a line that says <name> is <age> years old. and make the
whole line italic.
If statements
1. Create an if statement that will print <name> has blue eyes if the variable
blueeyes is true.
2. Add a part to your if statement that will print Eye colour unknown if the variable
blueeyes is not true
Calculations
1. Create a variable called badgers. Initialise it to 10 badgers.
2. Create a variable called mushrooms. There are currently 100 mushrooms.
3. Print a statement detailing how many badgers and mushrooms there are currently.
4. Using a simple division calculation, print out a statement about how many
mushrooms each badger will get, assuming the mushrooms are evenly divided. How
many mushrooms are left over?
5. Create a variable called babybadgers. Each badger couple has one child. Using a
simple calculation work out how many extra badgers there are now and store this
value inside babybadgers.
6. Six mushrooms are trampled and 31 mushrooms are eaten by a snake. Write code to
change the value of the variable mushrooms to reflect this.
7. Write a statement to show how many mushrooms each badger gets now that the
new baby badgers are also eating the mushrooms.
8. If badgers do not get more than 5 mushrooms each, they will be hungry. Using an if
statement, decide whether the badgers are too hungry or are just right.
13
User input
This is probably slightly more complex than in the language you have already studied,
because of the fact that PHP is a server side language. Heres how it works in PHP:
Array key
username
Value
(What you typed in the box)
14
So on our processing page (in this case page2.php) we can put the following code to see
what the user typed in the box:
<?php
print $_POST[username];
?>
We often want to see everything that was $_POST ed to the next page for debugging
purposes. You can print the whole $_POST array on the processing page like this:
<?php
print <pre>;
print_r( $_POST );
print </pre>;
?>
This would produce the following output if I typed in awesomezz in the box:
The $_POST array is global so you can use it however you like on this page:
You can add more fields to your input page, they will be referenced in the $_POST array
with the name attribute as their key, e.g. whatever is typed into this field
<input type=text name=batman>
will become the variable
$_POST[batman];
on the processing page. (You can obviously decide on sensible variable names yourself!)
15
16
See if you can understand what the code on the next page does, and add
suitable comments (the comment escape is // in PHP) to explain what is
happening:
17
<?php
if(empty($_GET)){
$_GET['page']=1;
}
$previous = $_GET['page'] - 1;
$next = $_GET['page'] + 1;
if($_GET['page'] != 1){
print "<a
href=\"paginator.php?page=$previous\">Previous</a> ";
}
if($_GET['page'] != 5){
print "<a href=\"paginator.php?page=$next\">Next</a>";
}
?>
18
19
Exercise 3
Alter your code from Event 2 to make it print out the correct row number inside each table
cell
Row 1
Row 2
Exercise 4
Write a program to automatically print out a one column table with alternating cell
background colours. You should be able to vary the amount of rows in a loop (see part 1)
this will help you!
1
2
3
4
5
This is the HTML code to help you:
<table>
<tr><td bgcolor=white>Cell</td></tr> // Print this $rows
times
<tr><td bgcolor=grey>Cell</td></tr>
.etc
</table>
Hint: If you want to decide whether a row is odd or even, you can use modulus:
$result = $counter % 2;
This divides $counter by 2 and puts the value of the remainder in the variable
$result it will either be 0 (even) or 1 (odd)
So then you can do a check: if $result is 0 (print white) else (print grey)
Exercise 5
Anyone who can manage this is a true Programming God or Goddess!
Can you make a checkerboard effect?
R1 C1
R2 C1
R1 C2
R2 C2
R1 C3
R2 C3
R1 C4
R2 C4
R1 C5
R2 C5
20
To create a user account for yourself so that you can connect to databases, click on
Privileges at the top and then click on Add a new user
Choose a username.
Host should be localhost
Choose a password
Dont click on generate
password!
Then scroll down and tick all of
the boxes (click on check all) to
make your user able to do
everything.
Then click the Create User
button
Creating a database
Now that you have a user account, you need to create a database. Click on the Databases
tab at the top:
Type the name of your database in the box and click Create. You can ignore the Collation
drop down. I called mine shoutbox because it is going to be for the project we will do later.
Dont use any spaces in your database name use underscores or camel/Pascal
case to distinguish between words.
You should see the name of your database appear in the list on the left. You can click on its
name to see it (there is nothing inside it yet).
Creating a table
When you have clicked on your database in the left hand side list you will be given an
opportunity to create a table.
Type the name of the table and the number of columns inside the boxes. I am going to call
my table shouts and I want 3 columns again, this is for our mini project that is coming up.
22
You will be asked to fill in the details for your table. Column is the field name, Type is the
data type of this field, Length/values is how long a space to reserve. You can set which field
is the primary key by selecting an option for it in the Index drop down.
Here is how I am going to fill in this form for my shouts table:
As you have probably figured out by now, Im working up to showing you how to create a
basic project a shoutbox! This is a bit like a very basic Facebook wall, with a box where a
user can write comments and the previous comments also displayed.
23
Obviously, fill in your own MySQL user, password and database name!
Then, whenever you need to connect to the database in a program, use the line:
<?php require_once(connection.php); ?>
This will grab the contents of the connection.php file and insert it into the page so that you
can use the $link variable as the connection youve already set up.
Why do I need a separate file? Cant I just put the connection line on the top
of each page? Well yes, you can. But imagine if you change your server
details which will definitely happen if you are testing your site on XAMPP
and uploading to an online webserver later on. Youll have to change the
details in every single page. If you put them in a connection file and require that
file wherever a connection is needed, you only need to change the details once in
the connection file instead of everywhere. Genius!
24
To make a larger box like the one above, you could use a <textarea>, the code looks like this:
<textarea name=shout></textarea>
If you cant remember how to make the form, have a look on page 14 for some tips. You can
style the form to your liking using CSS if you want to make it look prettier.
Processing the data
When the user types their shout in the box and clicks the button, the code should send this
data to a processing page called send.php
This means that the form action inside index.php should be <form
action=send.php>
Create and save a file called send.php inside the shoutbox folder in htdocs
25
Lines 1-13 are PHP code to insert the shout into the database. Lines 15-24 are HTML code
which provides a meta refresh on line 17 the code specifies to wait 0 seconds and then go
to index.php. This means that once the page is done with inserting the data into the
database, it redirects quickly to the first page.
If you like the cartoon on the front page of this booklet, you may be worried about
validation and SQL injection these are improvements you can make to the shoutbox, see
page 30 for details.
26
This is some validation I am checking that the shout they entered was not an empty string.
I could also have done it this way:
if( !empty($_POST[shout]) ) {
This checks whether the variable $_POST[shout] is not empty. (Dont forget we can refer to
what the user typed in as $_POST[shout] because it is passed to this page in the $_POST
array, and it has the index shout because that was the name of our textarea on index.php)
This part looks a bit technical, but it isnt. The first argument on line 8 is the database link
variable that we created in the connection.php file. The second argument is the query itself.
In the above code, on line 11 we are using concatenation to put the $_POST[shout]
variable inside the query. If the amount of quotes messes with your head, try renaming the
variable (line 8) and then you can use its short name on line 9. It works exactly the same but
its a poor and inefficient way of coding and you should try to understand the concatenation
method above if you can.
The or die part means that if the query cannot be done for whatever reason, the page
should stop executing and give us a mysql error message so that we can debug it.
27
Go back and edit your index.php file, and after the code for the form add a PHP section
A general example
Here is a general example of how to write a SELECT query to get data from your database
// Write the query
$query = SELECT fieldname FROM tablename;
// Execute the query
$result = mysqli_query($link, $query);
In this example, you specify which fields you would like from which table, when you write
the query.
In this example, the results are put one by one into an array called $data
$data = mysqli_fetch_assoc($result);
You can then reference each field by its name
e.g. if you had a field called username you could use...
print $data[username];
...if you had a field called dateofbirth you could use
print $data[dateofbirth];
28
On lines 20-21 I do a query in exactly the same way as we discussed before except that
this is a SELECT query to get data from the database, and not an INSERT query to put data in
the database.
Lines 24-27 are a loop which iterates through all of the rows of data returned by the query,
printing out the shout text and a HTML newline character (<br>).
29
30