COM 366 – Web Database Development

Download Report

Transcript COM 366 – Web Database Development

COM 366 – Web Database
Development
Introduction to XHTML and PHP
Module Aims
• Aims
– To increase the student’s awareness of current
developments in the field of web database
technologies and provide an understanding of the
problems associated with the creation of web
developments that use these technologies.
– To develop the skills necessary to create interactive,
professional data-driven web developments that
could be used in different types of businesses and ecommerce environments and that are produced using
open-source technologies
CW Description
Assignment
Assignment 1: PHPMySQL practical class tests
(open book on Practicals)
Assignment 2: PHPMySQL Closed Book Class
Test (blackboard)
Assignment 3: Project –
Database Driven Web
Development
Total
Contribution to CW %
Due Date
30%
Weeks 2,4,6,8 and 10
30%
Week 11
40%
Week 12
100%
Module & CW Information
• Detailed CW and Module Information can be
found on the Module Website:
http://www.scis.ulster.ac.uk/~jose
• In General it will take between 6 and 10 hours
of work to complete each practical
Introduction to PHP & MySQL
Laboratory Setup
PHP - MySQL
• Commercial Sites:
– Apache
– PHP
– MySQL
– XAMP (WAMP – MAMP)
• Required Tools
– Text Editor or a Program like Dreamweaver
Installing XAMP
• If you are working from your laptop, it is time to
download and install XAMP:
– Windows: Download and Install WAMP Server
– MAC: Download and Install MAMP
– Leave all the settings as default except the browser
(change to your preferred browser: I recommend
Chrome, Firefox or Safari)
– Once Installed, your files for this module need to be
stored in the following folder (also applies to the lab
machines: c:/wamp/www
– Task: Create a folder with your name inside this folder
Stopping IIS
• Next step (only if
you are working in
the lab) – you
need to stop IIS –
go to:
– CONTROL PANEL

ADMINISTRATIVE
TOOLS  Internet
Information
Service (IIS)
Manager 
Stopping IIS
– At the top
right hand
side of the
screen click
STOP
Configuring XAMP
• Now is time to Start WAMP Server:
– On the desktop click start wampserver; a red “w”
icon should appear in your taskbar, it should go
from red, to orange to green – once it is green we
are ready to go
Starting WAMP
Start WampServer
TaskBar – Red “W”
Starting WAMP
• Right click on the icon and
select: localhost (this should
open your browser with the
WAMP welcome page)
WAMP in Browser
Configuring Dreamweaver
• If you are working with your laptop, and don’t
have Dreamweaver, then use any available
text editor; just remember to save the files
with the correct extension and NOT as TEXT
• In Dreamweaver, you will need to create a site
to store your WAMP files:
Dreamweaver
– On the Dreamweaver
MENU BAR, click:
• SITE  New Site
Setting the Site
• On the Site Section
name the site, e.g. john
• Select the local folder
(as in the figure using
the disk to find it)
• Then Click on “Servers”
(second menu down on
the left)
Setting the Server
• Click on the “+” sign
under the window
• Change the Connect
using to Local Network
• Use the settings shown
on the figure
Your Files
• Click on the “Testing”
box and Save
First XHTML
XHTML CODE – PAGE STRUCTURE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>YOUR DOCUMENT TITLE</title>
</head>
<body>
…
YOUR CODE
…
</body>
</html>
HTML & XHTML
• HTML
– All Web pages are made up using HTML
(Hypertext Markup Language)
– Every Web Browser turns HTML code into the
stylized web page seen by the user
• XHTML
– The World Wide Web Consortium (W3C) – which
is the group responsible for defining HTML and
other protocols created XHTML as a transition
between HTML and XML
XHTML
• XHTML is almost exactly like HTML, with the
following differences:
– All tags are written in lowercase
– Nested tags must be well formed:
• i.e. you can’t write: <div><p>text</div></p> instead
you should write:
• <div><p>text</p></div>
– All tag attributes must be quoted:
• HTML: <table border=2>
• XHTML: <table border=“2”>
XHTML
– All tags must be closed:
• Many HTML tags have an open and close tag, i.e. <div
class=“class1”>text</div>, but a few don’t have implicit
closing tags: i.e. <hr>, <br>, <img> ad <input>
• To make this valid XHTML tags, you need to close them
by adding a space and a slash at the end, like this:
–
–
–
–
<br />
<hr />
<img src=“file.png” width=“100” height=“50” />
<input type=“text” name=“age” size=“3” />
First XHTML Page
Fill in the Title of the page (inside the <header></header> tags)
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Welcome to This page!</title>
</head>
Fill in the Body of the Page:
<body>
<h1>This is a Basic XHTML page</h1>
<br />
<p>Even with <span style="font-size:150%;">some</span> decoration, it's still not
very exciting.</p>
</body>
</html>
Open the Page on the Browser
The URL for your page is: http://localhost/yourfoldername/welcome.html
Styling
• Styling of XHTML is done using CSS (Cascading
Style Sheets) – They will be covered in detail in
Final Year – COM621
Introduction to PHP
Initial PHP
• To create a PHP script you should start exactly
as if you would if you were creating an XHTML
document from scratch
• In Dreamweaver:
– File New PHP Document
– This will create a PHP document that looks
EXACTLY as the Blank XHTML document
• Understanding the reason for this is vitally
important
How PHP Works
• PHP is a server-side language; the code that
you write in PHP resides on a host computer
that serves Web pages to Web Browsers
• When you go to a website (www.google.com
for example), your Internet Service Provider
(ISP) directs your request to the server that
hosts the www.google.com information
• The server reads the PHP code and processes
it according to its scripted directions
How PHP Works
PHP creates an HTML page on the fly based on
parameters of your choosing
Conceptual Summary PHP
• PHP is a server-side technology
– It does not run on the client (which is what the
web browsers are)
– However, the browsers understand HTML (and
JavaScript and CSS), so
– PHP will be used to generate the HTML that runs
in a Web Browser
– PHP is free, open-source code
PHP
• There are 3 main differences between a standard
HTML document and a PHP document:
1. PHP scripts should be saved with the .php file extension
2. The PHP code is placed within the following tags:
•
•
Start tag: <?php
End tag: ?>
3. PHP Scripts must run on a PHP-enabled Web server
•
•
HTML pages can be viewed on any computer
PHP must always be run through a URL (i.e.
http://something/page.php)
PHP
•
In the lab and on your laptop, WAMP will do the job
of a web server. WAMP/MAMP stands for:
•
•
•
•
Windows/Mac (Operating System)
Apache (web server technology)
MySQL (database technology)
Php (PHP:Hypertext Processor/HTML
scriptitng language)
Invented by Rasmus Lerdorf in 1994
embedded
First PHP Script
• This script will be useful to determine if the server being
used, supports PHP
• Code:
• On the Head section of your new PHP:
<title>First PHP Script</title>
• On the Body Section of your new PHP:
<body>
<?php
phpinfo()
?>
</body>
• Save the Script as: phpinfo.php
Testing the Script
• Once the file is saved in the WWW directory
(htdocs for a MAC) inside your folder, open
your favourite web browser and open the
following URL
http://localhost/yourfolder/phpinfo.php
Programming PHP
• Comments and White Space
– PHP comments are done placing two slashes in
front of the text to be commented or enclosing
multiple lines of comments in the /* and */
– A commented line will not be processed by the
PHP server
• It is good practice to use white space (blank
lines, tabs, and other extra space) to make
your code easier to write, read and maintain
Programming PHP
• Well written scripts:
– Place blank lines between sections of code
– Nest elements one tab-stop in from their parent
element
– Generally space out the page nicely
• These techniques are the trademark of
professionally written code
Code Comments
all PHP script must be
enclosed between these tags
<?php
// comment lines are indicated by the // symbol
/* Multiple line comments can be enclosed within
these marks. Usually used to describe the
functionality of a part of your code */
statements here;
// note: all PHP statements end with a semicolon ‘;’
?>
38
Variables
• A variable is best thought of as a container for
data
• Once a variable has been assigned a value,
that variable can be altered, printed to the
browser, saved to a database, emailed, etc.
• Variables in PHP are flexible: you can put data
into a variable, retrieve it (without affecting
the value of the variable), put new data in and
continue the cycle as necessary
Variables
• Variables in PHP are also temporary:
– They only exist (have value) for the duration of a
script
– Once the user clicks a link or submits a form, the
variables cease to exist unless you take special
measures to extend their longevity
• There are some variables that are predefined
in PHP (you don’t need to create them again).
– i.e: $_SERVER, $_SESSION, $_COOKIE, etc.
• The print_r() function can be used to view the
value stored in a variable
• Create a new PHP file named: variables.php
and place the following code:
Displaying Variable Content
Variables - Syntax
• All variable names must be preceded by a
dollar ($) sign
• Following the dollar sign, the variable name
must begin with either a letter (A-Z, a-z) or an
underscore (_). It can’t begin with a number
• The rest of the variable name can contain any
combination and quantity of letters,
underscores, and numbers
Variables - Syntax
• You may not use spaces within the name of a
variable (underscore is normally used to
separate words)
• Variable
names
are
CASE-SENSITIVE!
Consequently, $variable and $Variable are two
different constructs
Types of Variables
• There are 3 basic types of variables: numbers,
strings and arrays
• In PHP, numbers can be either
– Integers (positive or negative) i.e. 1, 1972, -1
– Floating point (positive or negative) 1.0, 19.72, -1.0
Types of Variables
• A string is any number of characters enclosed within a
pair of either single (') or double (") quotation marks.
They can contain any combination of letters, numbers,
symbols and spaces. Strings can contain variables:
"Hello World!”
"Hello, $first_name!”
"1 1/4”
"24.12.2011”
"1995”
''
Strings:
Operators
String Manipulation
Description
Example
Concatenation(.)
Merges 2 or more strings
together
$st1 = hello;
$st2 = world;
Sfst = $st1.$st2
Equal (==) and Identical
(===)
Check that two strings are
equal or identical – when
comparing string that do
not begin with a number
are seen as 0 by the
language
$st1=“hello”
$st2=“hello”
$st3=0
$st1==$st2  True
$st2==$st3  True (0=0)
$st2===$st3  False
String
Functions
Function
Description
printf()
Displays (prints) a formatted string
sprintf()
Saves a formatted string in a variable
fprintf()
Prints a formatted string to a file
number_format()
Formats numbers as strings
Common String
Functions
Function
Description
Example
strlen()
Finds the length of a string
echo strlen("Hello World"); 11
strtoupper()
Converts the string to
uppercase
strtolower()
Converts the string to
lowercase
ucfirst()
Converts the first letter in
a string to uppercase
ucwords()
Converts the first letter in
each word of a string to
uppercase
Common String
Functions
Function
Description
Example
strcmp()
Compares two strings (case strcmp(‘Dan’,’Daniel’)  -3
sensitive)
returns 0 if equal, <0 of
st1 smaller and >0 if st1
bigger
strcasecmp()
Compares two strings (not
case sensitive)
new york is equal to New
York
str_repeat()
Repeats the string
str_repeat(input,multiplier)
print str_repeat(“-”,30) 
print 30 dashes
Common String
Functions
Function
Description
Example
strchr()
Finds the first occurrence of a
strchr(string, character)
character in a string and returns
it and all characters to end of
strchr(“[email protected]”,”.”)  .ac
the string
strichr()
Case insensitive form of strchr()
strrchr()
Finds last occurrence of a
character on a string and
returns it and all characters to
end of the string
strchr(“[email protected]”,”a”)  ac
substr()
returns parts of a string
specified by start position and
length
substr (string,start,[length])
start and length are integers
Add Slashes
Special Characters
• When a form sends a word like O’Neil to a php script, the script will
interpret the apostrophe as an either opening or closing of single
quotes and that will not allow the script to work. In order for it to
work, the apostrophe needs to be send preceded by an slash, i.e.
O\’Neil.
• These are called “escaped” characters
• The addcslashes() and addslashes() functions are used to “escape”
backslash character when inserted into a database.
• The escaped characters are:
– Single and Double Quotes
– The Backslash itself (\)
– NULL
Add Slashes
Special Characters
• The PHP directive magic_quotes_gpc() is on by
default and it runs addslashes() on all $_GET,
$_POST and $_COOKIE data.
• DO NOT USE addslashes() ON STRINGS THAT
HAVE ALREADY BEEN ESCAPED
• You can use the get_magic_quotes_gpc()
function to see if magic_quotes is on:
if (get_magic_quotes_gpc()==1) {echo "on";} else {echo "off";}
• If instead of adding the escaped data into the
database, you only need to print it, then you
will need to use the stripcslashes() function to
print it
• The stripcslashes() functions removes
backslashes that precede quotation marks and
if there are double slashes, they become a
single slash.
Example
teststring.php FILE
<?php
$passstring = $_GET['field'];
$strippedstring = stripcslashes($passstring);
echo $passstring."<br />";
echo $strippedstring;
$link =
mysql_connect('localhost','student','student');
mysql_select_db('sandra',$link);
$query1 = "INSERT into input VALUES
(NULL,'$passstring')";
$result = mysql_query($query1,$link) or
die(mysql_error());
$query2 = "INSERT into input VALUES
(NULL,'$strippedstring')";
$result = mysql_query($query2,$link) or
die(mysql_error());
?>
HTML FORM
<body>
<form action="teststring.php" method="get">
<input type="text" name="field" />
<input type="submit" />
</form>
</body>
This Query will give an error when an
input like o’neil or o’connor is used in
form
Types of Variables
• Whereas a string or a number contains a single
value (they are called “scalars”), an array can
have more than one value assigned to it
• Arrays use “keys” to create and retrieve the
values they store. The resulting structure looks
similar to a two column spreadsheet
• The array structure in PHP is so flexible that it
can use either numbers or strings for both the
keys and the values
Types of Arrays
PHP has two types of arrays:
Indexed: uses numbers as the
keys
Associative: uses arrays as the
keys
Key
Value
Key
Value
0
Don
VT
Vermont
1
Jordan
FL
Florida
2
James
NY
New York
3
Jenny
TX
Texas
Note: The Arrays key is also called the index and both terms are used interchangeably
in the literature
<?php
$products=array('floral talc','body mist',
'perfumed powder','bath gel');
echo "<b>\$products is $products.<br>\n";
echo "\$products[0] is $products[0].<br>\n";
echo "\$products[1] is $products[1].<br>\n";
echo "\$products[2] is $products[2].<br>\n";
echo "\$products[3] is $products[3].<br>\n";
?>
<br><em>Let's add another element to the
array.</em><br>
<?php
$products[]='gentle soap';
echo "\$products[4] is $products[4].<br>\n";
?>
Example:
Indexed Array
<?php
$book=array('Title' => 'War and Peace',
'Author' => 'Tolstoy',
'Publisher' => "Oxford University Press"
);
$book['ISBN'] = "0192833987"; // Add a new
element
echo "<b>\$book is $book.<br>";
echo "\$book['Title'] ". $book['Title'] .".<br>";
echo "\$book['Author'] is ". $book['Author']
.".<br>";
echo "\$book['Publisher'] is ".
$book['Publisher'] .".<br>";
echo "\$book['Pages'] is ". $book['ISBN']
.".<br>";
?>
Example:
Associative Array
Programming PHP
• Sending text to the browser:
– There are 3 main functions that are used to send
text to the browser:
• print()
• printf()
• echo()
• Note that PHP is case insensitive
• We will be using primarily echo() and printf()
during the module
echo()
Examples
Use of echo with strings
<?php
$str = "Who's Anshe Chung?";
echo $str;
echo "<br />";
echo $str."<br />I don't know!";
?>
Echo with multiple lines
<?php
echo "This text
spans multiple
Lines but will print
in a single
line.";
?>
//Note to make the test
appear in multiple lines <pre>
must be used in the html
Examples
• Multiple Parameters
<?php
echo 'This ‘.'string ‘.'was ‘.'made ‘.'with multiple parameters';
?>
• Difference of single and double quotes – items within single
marks are treated literally, items within double quotes are
extrapolated (variable name is replaced with its value)
• So in the following example single quotes will print the
variable name, not the value:
<?php
$color = "red";
echo "Roses are $color";
echo "<br />";
echo 'Roses are $color';
?>
printf()
• The printf() function outputs a formatted
string
• The arg1, arg2, ++ parameters will be inserted
at percent (%) signs in the main string
• This function works "step-by-step"
• At the first % sign, arg1 is inserted, at the
second % sign, arg2 is inserted, etc.
Examples
Formatted Multiple Strings
<?php
$str = "Hello";
$number = 123;
printf("%s world. Day number
%u",$str,$number);
?>
Single String
<?php
$number = 123;
printf("%f",$number);
?>
printf()
Printing variables within
XHTML
<?php
print "<HTML><HEAD><TITLE> String Example</TITLE>
</HEAD>";
print "<BODY>";
$first = “Sandra";
$last = “Moffett";
$name = $first . $last; // string concatenation
print "<BR> name= $name";
print "</BODY></HTML>";
?>
name=Sandra Moffett
Conditional Statements
• if statement
if ( test condition )
statement to execute if condition is true;
• else clause
if ( test condition )
statement to execute if condition is true;
else
statement to execute if condition is false;
• elseif clause
if ( test condition1 )
statement to execute if condition1 is true;
elseif (test condition2)
statement to execute if condition2 is true;
Conditional Statements
•
if statement
if ( test condition ) {
one or more statements
}
•
else clause
if ( test condition ) {
one or more statements
} else {
one or more statements
}
•
elseif clause
if ( test condition ) {
one or more statements
} elseif (test condition) {
one or more statements
}
Note the difference between standard
and curly brackets
The if statement
Execute these statements
when $aver is greater than 40.
if ( $aver > 40 ) {
$Grade="Pass";
print "Grade=$Grade";
}
print "Your average was $aver";
•
70
Statement(s) to execute
regardless of test condition.
no semicolon appears at the end of the if statement itself.
Instead, curly brackets indicate a statement block, which
may contain semicolons as required.
The elseif clause
• specifies an additional test condition to check
$found = 0;
if ( $name == “John" ) {
print "Found - John";
$found = 1;
}
elseif ( $name == "Jane" ) {
print "Found - Jane";
$found = 1;
}
print "Name=$name and found=$found";
71
Execute these when
if condition is true .
Execute these when
its condition is true
but previous is false .
Execute
regardless of the
previous
test conditions.
The else clause
• used to specify a set of statements that execute when
all other test conditions in an if block are false
One or more statements to execute
if ( $name == “Mark" ) {
when test condition is true.
print “Found - Mark";
One or more statements to execute
when its test condition is true
}
but the previous test condition is false.
elseif ( $name == "Jane" ) {
One or more statements to execute
print “Found - Jane";
when the previous test condition(s) are false.
} else {
print "Could not validate Name=$name";
}
72
if statement - example
<?php
$mark = 92;
if ( $mark > 100 ) {
print “Invalid mark > 100”;
}
elseif ( $mark < 0 ) {
print “Invalid mark < 0”;
}
elseif ( $mark > 89 ){
print “Grade A”;
}
else {
print “Not A standard”;
}
?>
73
Switch Statements
•
•
•
if-elseif statements are good when we need to choose an action from a small
number of options but they become difficult to read/manage when the number of
options gets larger
Sometimes we may want the same action to occur for a number of options and a
different action for another set of options
For these cases, PHP has a control structure called “switch”. The switch statement is
not limited to numbers, strings can also be used
<?php
if ($i == 0) {
echo "i equals
} elseif ($i == 1)
echo "i equals
} elseif ($i == 2)
echo "i equals
}
?>
74
0";
{
1";
{
2";
Switch Statements
Example
<?php
switch ($i) {
case "apple":
echo "i is apple";
break;
case "bar":
echo "i is bar";
break;
case "cake":
echo "i is cake";
break;
}
?>
75
Switch Statements
• The switch statement executes statement by
statement. In the beginning, no code is executed
• When a case statement is found with a value that
matches the value of the switch expression PHP
begins to execute the statements
• PHP continues to execute the statements until
the end of the switch block, or the first time it
sees a break statement
• If you don't write a break statement at the end of
a case’s statement list, PHP will go on executing
the statements of the following case
76
Switch Statements
<?php
switch ($i) {
case 0:
echo "i equals 0 ";
case 1:
echo "i equals 1 ";
case 2:
echo "i equals 2 ";
}
?>
• If $i=0 the output will be:
– i equals 0 i equals 1 i equals 2
77
Switch Statements
• In order for the script to work, we need to add BREAKS:
<?php
switch ($i) {
case 0:
echo "i equals 0 ";
break;
case 1:
echo "i equals 1 ";
break;
case 2:
echo "i equals 2 ";
break;
}
?>
• If $i=1 the output will be:
– i equals 1
78
Switch Statements
• In a switch statement, the condition is
evaluated only once and the result is
compared to each case statement
– In an elseif statement, the condition is evaluated
again
– If your condition is more complicated than a
simple compare and/or is in a tight loop,
a switch may be faster
79
Looping statements
• PHP supports four types of looping (or iteration)
statement:
– The for loop
– The foreach loop
– The while loop
– The do-while loop
bounded iteration
unbounded iteration
• Used to repeat sections of code while certain
conditions exist
80
The for loop
• Typically used when you know how many
times the code should be repeated
Loop end condition
Initialization
expression. Sets the
initial value of "$i"
for ( $i = 0; $i < $max; $i++ ) {
Set of statements to repeat
note: use of
semicolons
81
}
Iteration expression
Increment $i each
loop iteration
The foreach loop
• Typically used to repeat a set of statements for every element in an array
An array value
Repeat the loop once for
every element in the list
foreach ($items_array
as $value
) {
Set of statements to repeat
}
• e.g.
$items_array = (“A”, “B”, “C”);
$value becomes “A” then “B” then “C”
82
The foreach loop
• A variation can use both key and value from the array
An array value.
Repeat the loop once for
every pair in the list
foreach ($items_array
• e.g.
}
as $key => $value
) {
Set of statements to repeat
$items_array = (“A” => “Blue”, “B” => “Red”, “C” =>
“Green”);
$key becomes “A” then “B” then “C”
$value becomes “Blue” then “Red” then “Green”
83
The while loop
• You use a while loop to repeat a section of
code as long as a test condition remains true
Repeat as long
as the conditional
test is true
Condition
enclosed
in parenthesis
while ( $ctr < $max ) {
Set of statements to repeat
}
84
The do-while loop
• Operates just like the while loop except that it
guarantees the statements inside the loop
with execute at least once
do {
The "do"
word starts
the loop
Set of statements to repeat
}
while ( $x < 100 )
Repeat while this
condition is true
85
Notes on infinite loops
• Always make sure your conditional statement is
appropriate in your for loops
– Using relativity comparisons are safer than absolute
ones
• If you need to repeat a loop 6 times starting at 1, have your
comparison be $x<7 rather than $x==6
• Unlike for loops where the control variable is
managed by the language, while and do-while
loops require manual management of a control
variable to avoid entering an infinite loop
– while ($x<6){…} will enter an infinite loop if $x is never
modified inside the while loop
86
Which loop to use?
• There is no rule that dictates which type of
loop to use
• Often the same problems can be solved using
different types of loop
• Use the construct which is the easiest for the
task at hand
87
Compound conditionals
• Logical conditional operators can test more than
one test condition at once when used with if
statements, while loops, and do-while loops
• For example,
while ( $x < $max && $found != ‘TRUE’ )
• For clarity, it may be useful to group test
conditions in parenthesis
while ( ($x < $max) && ($found != ‘TRUE’) )
88
The include() statement
• The include statement includes and evaluates the
specified file
• Files are included based on the file path given or,
if none is given, the include_path specified in
php.ini. If the file isn't found in the include_path,
include() will finally check in the calling script's
own directory and the current working directory
before failing
• The include() construct will emit a warning if it
cannot find a file
89
When to use include()?
•
•
•
•
90
Reuse of code
Setting up environmental variables
Reusable functions
Libraries
PHP Superglobals
• PHP provides a set of predefined variables accessible
from anywhere within the executing script and provide
us with substantial environmental information
• A script may require some variables be passed to it in
order to do something
• One way to “share” data between scripts is by means of
the $_GET superglobal
• The arguments to the script then get passed in the URL
that calls the script
• These are called CGI variables, or parameters
91
Sending arguments
(CGI variables) from a browser
• can be sent as a name-value pair after the
CGI program URL, signalled by ‘?’
The argument name is
mymark.
Its value is 96.
URL of the CGI
program to start.
http://localhost/example/module.php?mymark=96
Query String
The "?" signals argument to follow.

multiple name-value pairs can be sent, separated by
ampersands ‘&’
http://localhost/example/module.php?mygrd=56&myname=Ian
92
How do we read them?
• The $_GET variable is in reality an associative
array
• The index or “key” of the array is the name of
the variable
• The value of the array at the “key” is the value
of the variable.
http://localhost/example/module.php?mark=96
$a=$_GET[“mark”]); // a=96
93
The Undefined value
• Before variables are first assigned, they have
the undef value
– behaves as a zero when used as a number
– behaves as a zero-length string when used as a
string
• Many operators return undef when the
arguments are out of range or are not sensible
94
Testing for null values
• When receiving data from a browser, it is useful to
test whether a CGI variable has a value at all
$name = $_GET[“uname”];
if ($name) {
statement(s) to execute when $name has a value
} else {
statement(s) to execute when $name has no value
}
• The first if condition evaluates to true is $name
has any value, otherwise the else clause will
execute
Note CGI stands for COMPUTER GATEWAY INTERFACE
95
PHP operators
96
OPERATOR
USAGE
TYPE
+
Addition
Arithmetic
-
Subtraction
Arithmetic
*
Multiplication
Arithmetic
/
Division
Arithmetic
%
Modulus (remained Arithmetic
of a division)
++
Increment
Arithmetic
--
Decrement
Arithmetic
=
Assigns a value to a
variable
Assignment
==
Equality
Comparison
!=
Inequality
Comparison
OPERATOR
USAGE
TYPE
<
Less than
Comparison
>
Greater than
Comparison
<=
Less than or equal to
Comparison
>=
Greater than or equal to
Comparison
!
Negation
Logical
AND
&&
And
Logical
OR
||
Or
Logical
_
Concatenation
String
XOR
Or not
Logical
.=
Concatenation to the
value of a variable
Combined concatenation
and assignment
+=
Adds to the value of a
variable
Combined concatenation
and assignment
-=
Subtracts from the value
of a variable
Combined concatenation
and assignment
97
Catching errors
• PHP provides a feature that is very useful for
catching errors:
– or die(‘error message’)
• Usage
include(‘myfile.php’)
or
die
(‘“myfile.php” not found’);
– Will attempt to load and evaluate myfile.php, and
output
an
error
“myfile.php”
not
found
if not successful.
• Execution of the script will exit on die
98