BIT 3202 - Internet Programming Notes
BIT 3202 - Internet Programming Notes
___________________________________________________________________________
Content
2
Web Application server programming
___________________________________________________________________________
o Use of $_GET and $_POST
5. PHP Functions ………………………………………………………………………….41
o Defining Function
o Arguments
o Calling function
o Return statement
o Multiple Functions
6. PHP Arrays……………………………………………………………………………….48
o Definition
o Features of Array
o Methods of Creating arrays
o Array Index
o Storing Array Element
o Processing Array
7. PHP and MySql Database programming ……...………………………………………51
o Introduction
o Creating database
o Creating Tables
o Connecting to the Database Server
o Selecting a Database
o Adding Data to a Table using INSERT
o Query Tables using SELECT
o Edit Records
o Deleting Records
8. Web Programming project ……………………………………………………………….61
3
Web Application server programming
___________________________________________________________________________
5
Web Application server programming
___________________________________________________________________________
• Server side scripting languages – Executive on server side – PHP, ASP, JSP,
Python
What is PHP?
6
Web Application server programming
___________________________________________________________________________
• PHP files have a file extension of ".php", ".php3", or ".phtml"
What is MySQL?
PHP + MySQL
• PHP combined with MySQL are cross-platform (you can develop in Windows and
serve on a Unix platform)
Why PHP?
• When someone visits your PHP webpage, your web server processes the PHP code. It
then sees which parts it needs to show to visitors(content and pictures) and hides the other
stuff(file operations, math calculations, etc.) then translates your PHP into HTML. After
the translation into HTML, it sends the webpage to your visitor's web browser.
7
Web Application server programming
___________________________________________________________________________
PHP - Capabilities
Think of PHP in terms of what it can do for you. PHP will allow you to:
• Reduce the time to create large websites.
• Create a customized user experience for visitors based on information that you have
gathered from them.
• Open up thousands of possibilities for online tools.
• Allow creation of shopping carts for e-commerce websites.
Prerequisite
Before starting this tutorial it is important that you have a basic understanding and experience
in the following:
• HTML - Know the syntax and especially HTML Forms.
• Basic programming knowledge - This isn't required, but if you have any traditional
programming experience it will make learning PHP a great deal easier.
Requrements
o Web server – Apache, IIS
o PHP Application
o Code Editor
o Web Browser – PHP enabled.
PHP - Syntax
• Syntax – Refers to the rules that must be followed to write properly structured
code. They govern the structure of any programming language
• PHP's syntax and semantics are similar to most other programming languages
(C, Java, Perl) with the addition that all PHP code is contained with a tag, of
sorts.
• All PHP code must be contained within the following...
o PHP Code:
<?php
?>
8
Web Application server programming
___________________________________________________________________________
or the shorthand PHP tag that requires shorthand support to be enabled
on your server...
<?
?>
If you are writing PHP scripts and plan on distributing them, we suggest that you use
the standard form (which includes the ?php) rather than the shorthand form. This will
ensure that your scripts will work, even when running on other servers with different
settings.
If you have PHP inserted into your HTML and want the web browser to interpret it
correctly, then you must save the file with a .php extension, instead of the standard
.html extension. So be sure to check that you are saving your files correctly. Instead of
index.html, it should be index.php if there is PHP code in the file.
Example Simple HTML & PHP Page
Below is an example of one of the easiest PHP and HTML page that you can create and still
follow web standards.
PHP and HTML Code:
<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
Display:
Hello World!
9
Web Application server programming
___________________________________________________________________________
If you save this file (e.g. helloworld.php) and place it on PHP enabled server and load it
up in your web browser, then you should see "Hello World!" displayed. If not, please
check that you followed our example correctly.
We used the PHP function echo to write "Hello World!" and we will be talking in
greater depth about this PHP function and many others later on in this tutorial.
The Semicolon!
As you may or may not have noticed in the above example, there was a semicolon after
the line of PHP code. The semicolon signifies the end of a PHP statement and should
never be forgotten. For example, if we repeated our "Hello World!" code several times,
then we would need to place a semicolon at the end of each statement.
PHP and HTML Code:
<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<?php
echo "Hello World! ";
White Space
10
Web Application server programming
___________________________________________________________________________
• As with HTML, whitespace is ignored between PHP statements. This means it is OK to
have one line of PHP code, then 20 lines of blank space before the next line of PHP
code. You can also press tab to indent your code and the PHP interpreter will ignore
those spaces as well.
PHP and HTML Code:
<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<?php
echo "Hello World!";
echo "Hello World!";
?>
</body>
</html>
Display:
Hello World!Hello World!
This is perfectly legal PHP code.
PHP - Echo
The PHP function echo is a means of outputting text to the web browser.
Outputting a String
<?php
11
Web Application server programming
___________________________________________________________________________
$myString = "Hello!";
echo $myString;
echo "<h5>I love using PHP!</h5>";
?>
Display:
Hello!
I love using PHP!
In the above example we output "Hello!" without a hitch. The text we are outputting is
being sent to the user in the form of a web page, so it is important that we use proper
HTML syntax!
In our second echo statement we use echo to write a valid Header 5 HTML statement.
To do this we simply put the <h5> at the beginning of the string and closed it at the end
of the string. Just because you're using PHP to make web pages does not mean you can
forget about HTML syntax!
It is pretty cool that you can output HTML with PHP. However, you must be careful
when using HTML code or any other string that includes quotes! The echo function
uses quotes to define the beginning and end of the string, so you must use one of the
following tactics if your string contains quotations:
o Don't use quotes inside your string
o Escape your quotes that are within the string with a backslash. To escape a
quote just place a backslash directly before the quotation mark, i.e. \"
o Use single quotes (apostrophes) for quotes inside your string.
See our example below for the right and wrong use of the echo function:
PHP Code:
<?php
// This won't work because of the quotes around specialH5!
echo "<h5 class="specialH5">I love using PHP!</h5>";
If you want to output a string that includes quotations, either use an apostrophe ( ' ) or
escape the quotations by placing a backslash in front of it ( \" ). The backslash will tell
PHP that you want the quotation to be used within the string and NOT to be used to end
echo's string.
o E.g echo “I Love programming in \”PHP\” “;
While there is only one type of comment in HTML, PHP has two types.
13
Web Application server programming
___________________________________________________________________________
o the single line and
o multiple comment.
The single line comment
It tells the interpreter to ignore everything that occurs on that line to the right of the
comment.
To do a single line comment type "//" and all text to the right will be ignored by PHP
interpreter.
PHP Code:
<?php
echo "Hello World!"; // This will print out Hello World!
echo "<br />Psst...You can't see my PHP comments!"; // echo "nothing";
// echo "My name is Humperdinkle!";
?>
Display:
Hello World!
Psst...You can't see my PHP comments!
Notice that a couple of echo statements are not evaluated because they commented t out
with the single line comment. This type of line commenting is often used for quick
notes about complex and confusing code or to temporarily remove a line of PHP code.
Multiple Line Comment
Similar to the HTML comment, the multi-line PHP comment can be used to comment
out large blocks of code or writing multiple line comments. The multiple line PHP
comment begins with " /* " and ends with " */ ".
PHP Code:
<?php
/* This Echo statement will print out my message to the
the place in which I reside on. In other words, the World. */
echo "Hello World!";
14
Web Application server programming
___________________________________________________________________________
Display:
Hello World!
One of the best commenting practices that I can recommend to new PHP programmers is...
USE THEM!! So many people write complex PHP code and are either too lazy to write
good comments or believe the commenting is not needed. However, do you really
believe that you will remember exactly what you were thinking when looking at this
code a year or more down the road?
Let the comments permeate your code and you will be a happier PHPer in the future.
Use single line comments for quick notes about a tricky part in your code
Use multiple line comments when you need to describe something in greater depth
than a simple note.
15
Web Application server programming
___________________________________________________________________________
PHP VARIABLES
A variable is a means of storing a value, such as text string "Hello World!" or the
integer value 4. A variable can then be reused throughout your code, instead of having
to type out the actual value over and over again.
In PHP you define a variable with the following form:
$variable_name = Value;
If you forget that dollar sign at the beginning, it will not work. This is a common
mistake for new PHP programmers!
Note: Also, variable names are case-sensitive, so use the exact same capitalization
when using a variable. The variables $a_number and $A_number are different
variables in PHP's eyes.
A Quick Variable Example
To store a value, first want to make a variable name and then set that equal to the
value to store. See example below for the correct way to do this.
PHP Code:
<?php
$hello = "Hello World!";
$a_number = 4;
$anotherNumber = 8;
?>
Note for programmers: PHP does not require variables to be declared before being initialized.
There are a few rules that you need to follow when choosing a name for your PHP variables.
PHP variables must start with a letter or underscore "_".
PHP variables may only be comprised of alpha-numeric characters and underscores.
a-z, A-Z, 0-9, or _ .
Variables with more than one word should be separated with underscores.
$my_variable
16
Web Application server programming
___________________________________________________________________________
Variables with more than one word can also be distinguished with capitalization.
$myVariable
Echoing Variables
Echoing variables is very easy. The PHP developers put in some extra work to make
the common task of echoing all variables nearly foolproof!
No quotations are required, even if the variable does not hold a string. Below is the
correct format for echoing a variable.
PHP Code:
<?php
$my_string = "Hello Bob. My name is: ";
$my_number = 4;
$my_letter = ‘a’;
echo $my_string;
echo $my_number;
echo $my_letter;
?>
Display:
Hello Bob. My name is: 4a
<?php
$my_string = "Hello Bob. My name is: ";
17
Web Application server programming
___________________________________________________________________________
Display:
Hello Bob. My name is: Bobetta
Hi, I'm Bob. Who are you? Hello Bob. My name is:
Hi, I'm Bob. Who are you? Hello Bob. My name is: Bobetta
This combination can be done multiple times, as the example shows. This method of
joining two or more strings together is called concatenation
PHP - Strings
In the above example the first string will be stored into the variable $my_string, while
the second string will be used in the echo function and not be stored.
Remember to save your strings into variables if you plan on using them more than
once! Below is the output from our example code. They look identical just as we
thought.
18
Web Application server programming
___________________________________________________________________________
Display:
Tizag - Unlock your potential! Tizag - Unlock your potential!
If you want to use a single-quote within the string you have to escape the single-quote
with a backslash \ . Like this: \' !
PHP Code:
We have used double-quotes and will continue to use them as the primary method for
forming strings. Double-quotes allow for many special escaped characters to be used
that you cannot do with a single-quote string. Once again, a backslash is used to escape
a character.
PHP Code:
Note: If you try to escape a character that doesn't need to be, such as an apostrophe, then the
backslash will show up when you output the string.
19
Web Application server programming
___________________________________________________________________________
These escaped characters are not very useful for outputting to a web page because HTML
ignore extra white space. A tab, newline, and carriage return are all examples of extra
(ignorable) white space. However, when writing to a file that may be read by human eyes these
escaped characters are a valuable tool!
PHP - String Creation Heredoc
The two methods above are the traditional way to create strings in most programming
languages. PHP introduces a more robust string creation tool called heredoc that lets the
programmer create multi-line strings without using quotations. However, creating a string
using heredoc is more difficult and can lead to problems if you do not properly code your
string! Here's how to do it:
PHP Code:
$my_string = <<<TEST
Tizag.com
Webmaster Tutorials
Unlock your potential!
TEST;
echo $my_string;
There are a few very important things to remember when using heredoc.
Use <<< and some identifier that you choose to begin the heredoc. In this example we
chose TEST as our identifier.
Repeat the identifier followed by a semicolon to end the heredoc string creation. In this
example that was TEST;
The closing sequence TEST; must occur on a line by itself and cannot be indented!
Another thing to note is that when you output this multi-line string to a web page, it will not
span multiple lines because we did not have any <br /> tags contained inside our string! Here is
the output made from the code above.
20
Web Application server programming
___________________________________________________________________________
• Three categories;
o Sequence – default control structure where the statements are executed in the
order they appear in the code.
o Selection – IF and switch case
o Iteration/Loop – while, do while and for loops
• if statement - use this statement to execute some code only if a specified condition is
true
• if...else statement - use this statement to execute some code if a condition is true and
another code if the condition is false
• if...elseif....else statement - use this statement to select one of several blocks of code to
be executed
The If Statement
The PHP if statement is very similar to other programming languages use of the if
statement.
Example: Think about the decisions you make before you go to sleep. If you have
something to do the next day, say go to work, school, or an appointment, then you will
set your alarm clock to wake you up. Otherwise, you will sleep in as long as you like!
This simple kind of if/then statement is very common in every day life and also appears
in programming quite often. Whenever you want to make a decision given that
something is true (you have something to do tomorrow) and be sure that you take the
appropriate action, you are using an if/then relationship.
21
Web Application server programming
___________________________________________________________________________
The PHP if statement tests to see if a value is true, and if it is a segment of code will be
executed.
The if statement is necessary for most programming, thus it is important in PHP.
Imagine that on January 1st you want to print out "Happy New Year!" at the top of your
personal web page. With the use of PHP if statements you could have this process
automated, months in advance, occurring every year on January 1st.
This idea of planning for future events is something you would never have had the
opportunity of doing if you had just stuck with HTML.
If Statement Example
PHP Code:
$my_name = "someguy";
if ( $my_name = = "someguy" ) {
echo "Your name is someguy!<br />";
}
echo "Welcome to my homepage!";
Display:
Your name is someguy!
Welcome to my homepage!
We were comparing the variable $my_name with "someguy" to see if they were equal?
In PHP you use the equivalent operator (= = ) to compare values.
Additionally, notice that because the if statement turned out to be true, the code
segment was executed, printing out "Your name is someguy!".
Explanation
First set the variable $my_name equal to "someguy".
Next use a PHP if statement to check if the value contained in the variable
$my_name was equal to "someguy"
22
Web Application server programming
___________________________________________________________________________
The comparison between $my_name and "someguy" was done with a "= =", not a
single equals"="! A single equals is for assigning a value to a variable, while a double
equals is for checking if things are equal.
Translated into English the PHP statement ( $my_name = = "someguy" ) is (
$my_name is equal to "someguy" ).
$my_name is indeed equal to "someguy" so the echo statement is executed.
A False If Statement
What happens when a PHP if statement is not true, in other words, false?. Consider that we
changed the above example to:
PHP Code:
$my_name = "anotherguy";
if ( $my_name == "someguy" ) {
echo "Your name is someguy!<br />";
}
echo "Welcome to my homepage!";
Display:
Welcome to my homepage!
Here the variable contained the value "anotherguy", which is not equal to "someguy".
The if statement evaluated to false, so the code segment of the if statement was not
executed. When used properly, the if statement is a powerful tool to have in your
programming.
The if Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax
if (condition) code to be executed if condition is true;
23
Web Application server programming
___________________________________________________________________________
The following example will output "Have a nice weekend!" if the current day is Friday:
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri") echo "Have a nice weekend!";
?>
</body>
</html>
Notice that there is no ..else.. in this syntax. The code is executed only if the specified
condition is true.
Use the if....else statement to execute some code if a condition is true and another code if a
condition is false.
Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Example
The following example will output "Have a nice weekend!" if the current day is Friday,
otherwise it will output "Have a nice day!":
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
</body>
</html>
24
Web Application server programming
___________________________________________________________________________
If more than one line should be executed if a condition is true/false, the lines should be
enclosed within curly braces:
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
{
echo "Hello!<br />";
echo "Have a nice weekend!";
echo "See you on Monday!";
}
?>
</body>
</html>
Use the if....elseif...else statement to select one of several blocks of code to be executed.
Syntax
if (condition)
code to be executed if condition is true;
elseif (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Example
The following example will output "Have a nice weekend!" if the current day is Friday, and
"Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice
day!":
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
elseif ($d=="Sun")
25
Web Application server programming
___________________________________________________________________________
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
</body>
</html>
Syntax
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from both label1 and label2;
}
This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each
case in the structure. If there is a match, the block of code associated with that case is
executed. Use break to prevent the code from running into the next case automatically.
The default statement is used if no match is found.
Example
<html>
<body>
<?php
26
Web Application server programming
___________________________________________________________________________
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
}
?>
</body>
</html>
With the use of the switch statement you can check for all these conditions at once, and
the great thing is that it is actually more efficient programming to do this. A true win-
win situation!
The way the Switch statement works is it takes a single variable as input and then
checks it against all the different cases you set up for that switch statement. Instead of
having to check that variable one at a time, as it goes through a bunch of If Statements,
the Switch statement only has to check one time.
PHP Switch Statement Example
In our example the single variable will be $destination and the cases will be: Las
Vegas, Amsterdam, Egypt, Tokyo, and the Caribbean Islands.
PHP Code:
$destination = "Tokyo";
echo "Traveling to $destination<br />";
switch ($destination){
case "Las Vegas":
27
Web Application server programming
___________________________________________________________________________
Display:
Traveling to Tokyo
Bring lots of money
The value of $destination was Tokyo, so when PHP performed the switch operating on
$destination in immediately did a search for a case with the value of "Tokyo". It found
it and proceeded to execute the code that existed within that segment.
You might have noticed how each case contains a break; at the end of its code area.
This break prevents the other cases from being executed. If the above example did not
have any break statements then all the cases that follow Tokyo would have been
executed as well. Use this knowledge to enhance the power of your switch statements!
The form of the switch statement is rather unique, so spend some time reviewing it
before moving on. Note: Beginning programmers should always include the break; to
avoid any unnecessary confusion.
PHP Switch Statement: Default Case
28
Web Application server programming
___________________________________________________________________________
You may have noticed the lack of a place for code when the variable doesn't match our
condition. The if statement has the else clause and the switch statement has the default
case.
It's usually a good idea to always include the default case in all your switch statements.
Below is a variation of our example that will result in none of the cases being used
causing our switch statement to fall back and use the default case. Note: there is no
case before default.
PHP Code:
29
Web Application server programming
___________________________________________________________________________
Display:
Traveling to New York
Bring lots of underwear!
PHP - Loops
Repetitive tasks are always a burden to us. Deleting spam email, sealing 50 envelopes, and
going to work are all examples of tasks that are repeated. The nice thing about programming is
that you can avoid such repetitive tasks with a little bit of extra thinking. Most often these
repetitive tasks are conquered in the loop.
The idea of a loop is to do something over and over again until the task has been completed.
Before we show a real example of when you might need one, let's go over the structure of the
PHP while loop.
While loop
do while loop
for loop
The function of the while loop is to do a task over and over as long as the specified conditional
statement is true. This logical check is the same as the one that appears in a PHP if statement to
determine if it is true or false. Here is the basic structure of a PHP while loop:
30
Web Application server programming
___________________________________________________________________________
This isn't valid PHP code, but it displays how the while loop is structured. Here is the break
down of how a while loop functions when your script is executing:
1. The conditional statement is checked. If it is true, then (2) occurs. If it is false, then (4)
occurs.
2. The code within the while loop is executed.
3. The process starts again at (1). Effectively "looping" back.
4. If the conditional statement is false, then the code within is not executed and there is no
more looping. The code following the while loop is then executed like normal.
Example
$times = 5;
$x = 0;
while ($x < $times) {
echo "Hello World";
++$x;
}
Imagine that you are running an art supply store. You would like to print out the price chart for
number of brushes and total cost. You sell brushes at a flat rate, but would like to display how
much different quantities would cost. This will save your customers from having to do the
mental math themselves.
You know that a while loop would be perfect for this repetitive and boring task. Here is how to
go about doing it.
$brush_price = 5;
$counter = 10;
31
Web Application server programming
___________________________________________________________________________
Display:
Quantity Price
10 50
20 100
30 150
40 200
50 250
60 300
70 350
80 400
90 450
100 500
Pretty neat, huh? The loop created a new table row and its respective entries for each quantity,
until our counter variable grew past the size of 100. When it grew past 100 our conditional
statement failed and the loop stopped being used. Let's review what is going on.
1. We first made a $brush_price and $counter variable and set them equal to our desired
values.
32
Web Application server programming
___________________________________________________________________________
2. The table was set up with the beginning table tag and the table headers.
3. The while loop conditional statement was checked, and $counter (10) was indeed
smaller or equal to 100.
4. The code inside the while loop was executed, creating a new table row for the price of
10 brushes.
5. We then added 10 to $counter to bring the value to 20.
6. The loop started over again at step 3, until $counter grew larger than 100.
7. After the loop had completed, we ended the table.
You may have noticed that we placed slashes infront the quotations in the first echo statement.
You have to place slashes before quotations if you do not want the quotation to act as the end
of the echo statement. This is called escaping a character and it is discussed in our PHP Strings
lesson.
With proper use of loops you can complete large tasks with great ease.
Example 1
$times = 5;
$x;
for ($x=0; $x<$times;$x++)
{
33
Web Application server programming
___________________________________________________________________________
echo "Hello World";
}
Let us take the example from the while loop lesson and see how it could be done in a for loop.
The basic structure of the for loop is as follows:
Pseudo PHP Code:
Notice how all the steps of the loop are taken care of in the for loop statement. Each step is
separated by a semicolon: initiliaze counter, conditional statement, and the counter increment.
A semicolon is needed because these are separate expressions. However, notice that a
semicolon is not needed after the "increment counter" expression.
Here is the example of the brush prices done with a for loop .
PHP Code:
$brush_price = 5;
34
Web Application server programming
___________________________________________________________________________
It is important to note that both the for loop and while loop implementation of the price chart
table are both OK at getting the job done. However, the for loop is somewhat more compact
and would be preferable in this situation. In later lessons we will see where the while loop
should be used instead of the for loop.
A simple example that illustrates the difference between these two loop types is a conditional
statement that is always false. First the while loop:
PHP Code:
$cookies = 0;
while($cookies > 1){
echo "Mmmmm...I love cookies! *munch munch munch*";
}
Display:
As you can see, this while loop's conditional statement failed (0 is not greater than 1), which
means the code within the while loop was not executed. Now, can you guess what will happen
with a do-while loop?
PHP Code:
$cookies = 0;
do {
echo "Mmmmm...I love cookies! *munch munch munch*";
35
Web Application server programming
___________________________________________________________________________
Display:
Mmmmm...I love cookies! *munch munch munch*
The code segment "Mmmm...I love cookies!" was executed even though the conditional
statement was false. This is because a do-while loop first do's and secondly checks the while
condition!
36
Web Application server programming
___________________________________________________________________________
A very common application of PHP is to have an HTML form gather information from
a website's visitor and then use PHP to do process that information.
In the example below we will simulate a small business's website that is implementing
a very simple order form.
Imagine we are an art supply store that sells brushes, paint, and erasers. To gather order
information from our prospective customers we will have to make a page with an
HTML form to gather the customer's order.
First create an HTML form that will let our customer choose what they would like to
purchase. This file should be saved as "order.html"
order.html Code:
<html><body>
<h4>Tizag Art Supply Order Form</h4>
<form>
<select>
<option>Paint</option>
<option>Brushes</option>
<option>Erasers</option>
</select>
Quantity: <input type="text" />
<input type="submit" />
</form>
</body></html>
37
Web Application server programming
___________________________________________________________________________
Display:
Next alter our HTML form to specify the PHP page we wish to send this information to.
Also, we set the method to "post".
order.html Code:
<html><body>
<h4>Tizag Art Supply Order Form</h4>
<form action="process.php" method="post">
<select name="item">
<option>Paint</option>
<option>Brushes</option>
<option>Erasers</option>
</select>
Quantity: <input name="quantity" type="text" />
<input type="submit" />
</form>
</body></html>
The "order.html" is complete, let us continue on and create the "process.php" file which
will process the HTML form information.
We want to get the "item" and "quantity" inputs that we have specified in our HTML
form.
The proper way to get this information would be to create two new variables, $item and
$quantity and set them equal to the values that have been "posted". The name of this
file is "process.php".
process.php Code:
<html><body>
38
Web Application server programming
___________________________________________________________________________
<?php
$quantity = $_POST['quantity'];
$item = $_POST['item'];
echo "You ordered ". $quantity . " " . $item . ".<br />";
echo "Thank you for ordering from Tizag Art Supplies!";
?>
</body></html>
As you probably noticed, the name in $_POST['name'] corresponds to the name that we
specified in our HTML form.
Now try uploading the "order.html" and "process.php" files to a PHP enabled server and test
them out. If someone selected the item brushes and specified a quantity of 6, then the following
would be displayed on "process.php":
process.php Code:
A lot of things were going on in this example. Let us step through it to be sure you understand
what was going on.
1. We first created an HTML form "order.html" that had two input fields specified, "item"
and "quantity".
2. We added two attributes to the form tag to point to "process.php" and set the method to
"post".
3. We had "process.php" get the information that was posted by setting new variables
equal to the values in the $_POST associative array.
4. We used the PHP echo function to output the customers order.
39
Web Application server programming
___________________________________________________________________________
This HTML code specifies that the form data will be submitted to the "process.php"
web page using the POST method. The way that PHP does this is to store all the
"posted" values into an associative array called "$_POST". Be sure to take notice the
names of the form data names, as they represent the keys in the "$_POST" associative
array.
Now that you know about associative arrays, the PHP code from "process.php" should
make a litte more sense.
PHP Code Excerpt:
$quantity = $_POST['quantity'];
$item = $_POST['item'];
The form names are used as the keys in the associative array, so be sure that you never
have two input items in your HTML form that have the same name. If you do, then you
might see some problems arise.
PHP - GET
As mentioned before, the alternative to the post method is get. If we were to change our
HTML form to the get method, it would look like this:
40
Web Application server programming
___________________________________________________________________________
HTML Code Excerpt:
The get method is different in that it passes the variables along to the "process.php"
web page by appending them onto the end of the URL. The URL, after clicking submit,
would have this added on to the end of it:
"?item=##&quantity=##"
The question mark "?" tells the browser that the following items are variables. Now that we
changed the method of sending information on "order.html", we must change the "process.php"
code to use the "$_GET" associative array.
PHP Code Excerpt:
$quantity = $_GET['quantity'];
$item = $_GET['item'];
After changing the array name the script will function properly. Using the get method displays
the variable information to your visitor, so be sure you are not sending password information
or other sensitive items with the get method. You would not want your visitors seeing
something they are not supposed to!
41
Web Application server programming
___________________________________________________________________________
PHP FUNCTIONS
A function is just a name we give to a block of code that can be executed whenever we
need it.
For example, you might have a company motto that you have to display at least once on
every webpage. If you don't, then you get fired! Well, being the savvy PHP
programmer you are, you think to yourself, "this sounds like a situation where I might
need functions."
Creating Your First PHP Function
When you create a function, you first need to give it a name, like myCompanyMotto.
It's with this function name that you will be able to call upon your function, so make it
easy to type and understand.
The actual syntax for creating a function is pretty self-explanatory, but you can be the
judge of that. First, you must tell PHP that you want to create a function. You do this by
typing the keyword function followed by your function name and some other stuff
(which we'll talk about later).
Here is how you would make a function called myCompanyMotto. Note: We still have to fill in
the code for myCompanyMotto.
PHP Code:
<?php
function myCompanyMotto(){
}
?>
Note: Your function name can start with a letter or underscore "_", but not a number!
With a properly formatted function in place, we can now fill in the code that we want our
function to execute.
Do you see the curly braces in the above example "{ }"? These braces define where our
function's code goes. The opening curly brace "{" tells php that the function's code is
starting and a closing curly brace "}" tells PHP that our function is done!
We want our function to print out the company motto each time it's called, so that
sounds like it's a job for the echo function!
42
Web Application server programming
___________________________________________________________________________
PHP Code:
<?php
function myCompanyMotto(){
echo "We deliver quantity, not quality!<br />";
}
?>
That's it! You have written your first PHP function from scratch! Notice that the code that
appears within a function is just the same as any other PHP code.
Now that you have completed coding your PHP function, it's time to put it through a test run.
Below is a simple PHP script. Let's do two things: add the function code to it and use the
function twice.
PHP Code:
<?php
echo "Welcome to Tizag.com <br />";
echo "Well, thanks for stopping by! <br />";
echo "and remember... <br />";
?>
<?php
function myCompanyMotto(){
echo "We deliver quantity, not quality!<br />";
}
echo "Welcome to Tizag.com <br />";
myCompanyMotto();
echo "Well, thanks for stopping by! <br />";
echo "and remember... <br />";
myCompanyMotto();
43
Web Application server programming
___________________________________________________________________________
?>
Display:
Welcome to Tizag.com
We deliver quantity, not quality!
Well, thanks for stopping by!
and remember...
We deliver quantity, not quality!
Although this was a simple example, it's important to understand that there is a lot going on
and there are a lot of areas to make errors. When you are creating a function, follow these
simple guidelines:
1. Always start your function with the keyword function
2. Remember that your function's code must be between the "{" and the "}"
3. When you are using your function, be sure you spell the function name correctly
PHP Functions - Parameters
Another useful thing about functions is that you can send them information that the
function can then use. Our first function myCompanyMotto isn't all that useful because
all it does, and ever will do, is print out a single, unchanging string.
However, if we were to use parameters, then we would be able to add some extra
functionality! A parameter appears with the parentheses "( )" and looks just like a
normal PHP variable. Let's create a new function that creates a custom greeting based
off of a person's name.
Our parameter will be the person's name and our function will concatenate this name
onto a greeting string. Here's what the code would look like.
PHP Code with Function:
<?php
function myGreeting($firstName){
echo "Hello there ". $firstName . "!<br />";
}
?>
44
Web Application server programming
___________________________________________________________________________
When we use our myGreeting function we have to send it a string containing someone's name,
otherwise it will break. When you add parameters, you also add more responsibility to you, the
programmer! Let's call our new function a few times with some common first names.
PHP Code:
<?php
function myGreeting($firstName){
echo "Hello there ". $firstName . "!<br />";
}
myGreeting("Jack");
myGreeting("Ahmed");
myGreeting("Julie");
myGreeting("Charles");
?>
Display:
Hello there Jack!
Hello there Ahmed!
Hello there Julie!
Hello there Charles!
It is also possible to have multiple parameters in a function. To separate multiple parameters
PHP uses a comma ",". Let's modify our function to also include last names.
PHP Code:
<?php
function myGreeting($firstName, $lastName){
echo "Hello there ". $firstName ." ". $lastName ."!<br />";
}
myGreeting("Jack", "Black");
myGreeting("Ahmed", "Zewail");
myGreeting("Julie", "Roberts");
myGreeting("Charles", "Schwab");
?>
45
Web Application server programming
___________________________________________________________________________
Display:
Hello there Jack Black!
Hello there Ahmed Zewail!
Hello there Julie Roberts!
Hello there Charles Schwab!
PHP Functions - Returning Values
Besides being able to pass functions information, you can also have them return a value.
However, a function can only return one thing, although that thing can be any integer, float,
array, string, etc. that you choose!
How does it return a value though? Well, when the function is used and finishes executing, it
sort of changes from being a function name into being a value. To capture this value you can
set a variable equal to the function. Something like:
$myVar = somefunction();
Let's demonstrate this returning of a value by using a simple function that returns the sum of
two integers.
PHP Code:
<?php
function mySum($numX, $numY){
$total = $numX + $numY;
return $total;
}
$myNumber = 0;
echo "Before the function, myNumber = ". $myNumber ."<br />";
$myNumber = mySum(3, 4); // Store the result of mySum in $myNumber
echo "After the function, myNumber = " . $myNumber ."<br />";
?>
Display:
Before the function, myNumber = 0
After the function, myNumber = 7
When we first print out the value of $myNumber it is still set to the original value of 0.
However, when we set $myNumber equal to the function mySum, $myNumber is set equal to
46
Web Application server programming
___________________________________________________________________________
mySum's result. In this case, the result was 3 + 4 = 7, which was successfully stored into
$myNumber and displayed in the second echo statement!
47
Web Application server programming
___________________________________________________________________________
PHP ARRAYS
Defining Arrays with the array() Construct
The array() construct is useful when you want to assign multiple values to an array at one
time. Let's define an array called $users and assign four strings to it:
You can now access the third element in the $user array by using the index 2:
print $users[2];
print $users[2]."<br>";
for($i=0;$i<=3;$i++)
{
echo $users[$i]."<br>";
?>
Creating Arrays
By default, arrays are lists of values indexed by number. Values can be assigned to an array in
two ways: with the
• array() construct or
• using empty square brackets ([]).
48
Web Application server programming
___________________________________________________________________________
The array() construct is useful when you want to assign multiple values to an array at one
time. Let's define an array called $users and assign four strings to it:
Process array:
o Accessing, computations, sorting, printing out array elements.
¾ Access one element- use index of the element.
$marks[0]; // refer to 56
$x = $marks[0]+ $marks[3];
echo $x;
¾ Processing All elements
This is done by use of for loop.
Example
$marks=array (56,89,45,80,56);
for($i=0;$i<5;$i++)
{
echo $marks[$i];
echo “<br>”;
}
You can now access the third element in the $user array by using the index 2:
print $users[2];
This would return the string Betty. The index of an array element is placed between square
brackets directly after the array name. You can use this notation to either set or retrieve a value.
Remember that arrays are indexed from zero by default, so the index of any element in a
sequentially indexed array always is one less than the element's place in the list.
You can create a new array (or add to an existing one) by using the array identifier in
conjunction with the array name. The array identifier is a set of square brackets with no index
number or name inside it.
49
Web Application server programming
___________________________________________________________________________
Notice that we didn't need to place any numbers between the square brackets. PHP
automatically takes care of the index number, which saves you from having to work
out which is the next available slot.
$marks=array (10,20,10,40,30);
// create and inialize the array
$marks[]=10;
$marks[]=20;
$marks[]=10;
$marks[]=40;
$marks[]=30;
<?php
$users[] = " Bert";
$users[] = " Sharon";
$users[] = " Betty";
$users[] = " Harry";
for($i=0;$i<=3;$i++)
{
echo $users[$i]."<br>";
}
?>
50
Web Application server programming
___________________________________________________________________________
Capabilities
Allow to create database driven web application with the following capabilities:
• Add records to database through web forms
• Retrieve information from database to web pages
• Update database records
• Delete records from database through web pages
What is MySQL?
MySQL is a database.
A table is a collection of related data entries and it consists of columns and rows.
Databases are useful when storing information categorically. A company may have a database
with the following tables: "Employees", "Products", "Customers" and "Orders".
Database Tables
A database most often contains one or more tables. Each table is identified by a name (e.g.
"Customers" or "Orders"). Tables contain records (rows) with data.
The table above contains three records (one for each person) and four columns (LastName,
FirstName, Address, and City).
51
Web Application server programming
___________________________________________________________________________
Queries
With MySQL, we can query a database for specific information and have a recordset returned.
The query above selects all the data in the "LastName" column from the "Persons" table, and
will return a recordset like this:
LastName
Hansen
Svendson
Pettersen
Before you can access data in a database, you must create a connection to the database.
Syntax
mysql_connect(servername,username,password);
Parameter Description
servername Optional. Specifies the server to connect to. Default value is
"localhost:3306"
username Optional. Specifies the username to log in with. Default value is “root” or
the name of the user that owns the server process
password Optional. Specifies the password to log in with. Default is ""
Example 1
<?php
$host="localhost";
52
Web Application server programming
___________________________________________________________________________
$user="root";
$pwd="";
$db="musau";
$myconn=mysql_pconnect($host,$user,$pwd);
if(!$myconn)
{
//echo "Connection failed";
}
else
//echo "Connection established<br>";
?>
Example 2
In the following example we store the connection in a variable ($con) for later use in the script.
The "die" part will be executed if the connection fails:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
?>
Closing a Connection
The connection will be closed automatically when the script ends. To close the connection
before, use the mysql_close() function:
<?php
$con = mysql_connect("localhost","peter","abc123");
53
Web Application server programming
___________________________________________________________________________
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_close($con);
?>
After creating connection to database server next is to select the databse to use.
This is done by use of mysql_select_db () function.
Parameters:
Database name
Connection handle
Example
$mydb= mysql_select_db($db,$myconn);
if(!$mydb)
{
//echo "Database not selected";
}
else
//echo "Database Musau selected<br>";
if(!$result)
{
//echo "table not selected";
}
else
//echo "Table selected";
54
Web Application server programming
___________________________________________________________________________
The INSERT INTO statement is used to add new records to a database table.
Syntax
The first form doesn't specify the column names where the data will be inserted, only their
values:
The second form specifies both the column names and the values to be inserted:
Example
First create an HTML form that can be used to add new records to the "Customer" table.
55
Web Application server programming
___________________________________________________________________________
When a user clicks the submit button in the HTML form in the example above, the form data is
sent to "customer.php".
The "customer.php" file connects to a database, and retrieves the values from the form with the
PHP $_POST variables.
Then, the mysql_query() function executes the INSERT INTO statement, and a new record
will be added to the "Persons" table.
<?php
require_once('conn.php'); //call the connection code first
56
Web Application server programming
___________________________________________________________________________
echo "Record not added into the table";
}
else
echo "Recorded added successfully!";
?>
Syntax
SELECT column_name(s)
FROM table_name
To get PHP to execute the statement above we must use the mysql_query() function. This
function is used to send a query or command to a MySQL connection.
Example
The following example selects all the data stored in the "customer" table (The * character
selects all the data in the table):
<?php
require_once('conn.php');
//fetch the record per row and loop to fetch all the records
while($row = mysql_fetch_array($result))
{
echo "<tr>";
57
Web Application server programming
___________________________________________________________________________
echo "<td>".$row['custid']."</td>";
echo "<td>".$row['Names']."</td>";
echo "<td>".$row['Address']."</td>";
echo "<td>".$row['Product']."</td>";
echo "<td>".$row['Cost']."</td>";
echo "<td>".$row['Quantity']."</td>";
echo "</tr>";
}
echo "</table>";
?>
Syntax
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which
record or records that should be updated. If you omit the WHERE clause, all records will be
updated!
58
Web Application server programming
___________________________________________________________________________
To get PHP to execute the statement above we must use the mysql_query() function. This
function is used to send a query or command to a MySQL connection.
Example
Earlier in the tutorial we created a table named "Persons". Here is how it looks:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_close($con);
?>
After the update, the "Persons" table will look like this:
The DELETE FROM statement is used to delete records from a database table.
Syntax
DELETE FROM table_name
WHERE some_column = some_value
Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which
59
Web Application server programming
___________________________________________________________________________
record or records that should be deleted. If you omit the WHERE clause, all records will be
deleted!
To get PHP to execute the statement above we must use the mysql_query() function. This
function is used to send a query or command to a MySQL connection.
Example
The following example deletes all the records in the "Persons" table where LastName='Griffin':
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_close($con);
?>
60