CS 952 Database and Web Systems Development: Lectures 2 and 3: PHP: Hypertext Preprocessor
CS 952 Database and Web Systems Development: Lectures 2 and 3: PHP: Hypertext Preprocessor
Systems Development
2
Business 3-tier architecture
HTML
CSS
Javascript
PHP
MySQL
3
Server-side Scripting
• In the dark ages the internet was static – a true
hypertext. Useful for documentation but not shopping,
networking, twittering....
• Interactive web pages involve
– Client-side scripting
• JavaScript
– Server-side scripting
• cgi
• ssi
• ASP/JSP/PHP HTML
8
Content
• Basics
– variables, arrays, conditionals, loops and functions
• Handling forms
• Predefined values
• MySQL linkage
• String processing
• OO PHP
9
PHP: Hypertext Preprocessor
• Open-source technology
– It is free to download from www.php.net
• Source code and distribution are freely available
• Large community of developers
• Implementations for
– All major Unix, Linux, Mac OS and Windows operating
systems (plus others, even mobiles)
– Accessing different databases
• Especially MySQL but others including Microsoft Access
10
PHP
• PHP is an interpreted programming language
• PHP uses dynamic typing
• PHP has similar syntax to C/C++/Java/C#
• PHP can be procedural or object-oriented or
both
• PHP tempts spaghetti code, is criticised by
purists, but remains very popular
11
What is a PHP file?
13
How do I develop PHP?
• You write HTML with little bits of PHP code embedded in
between <?php ?> tags
– Saved in a .php file
– Server interprets them before delivering the page
– echo (or print) is used to output to screen
• All PHP statements end with a semicolon
• Example
– <?php print ("Hello World! "); ?>
– <h1>Today is:</h1> <?php echo date("d/m/Y"); ?>
14
Comments and Case-Sensitivity
• PHP supports 'C', 'C++' and Unix shell-style (Perl style)
comments
<?php
echo 'This is a test<br>'; // This is a one-line c++ style comment
/* This is a multi line comment
yet another line of comment */
echo 'This is yet another test<br>';
echo 'One Final Test<br>'; # This is a one-line shell-style comment
?>
• Keywords (e.g. if, else, while, echo), classes, functions and
user-defined functions in PHP are not case-sensitive but variables
are case-sensitive
15
PHP Variables and Types
• Variables hold values in memory
• All PHP variable names begin with $ followed either by
a letter or underscore, followed by any number of
letters, numbers, or underscores
– $title, $name, $age
• Variable names are case-sensitive
• Variables are not explicitly typed
$name = "Bob";
$age = 25;
16
PHP Types
• PHP is a loosely-typed language
– It automatically converts a variable to its correct type, depending upon its value
• Scalar types
– Boolean
• $x = true; $y = false;
– Numbers: Integer and Float
• $a = 10; $b = 13.4;
– String
• $message = "Hello World";
• Compound types
– Array
– Object
• PHP has the special data type NULL
• The function var_dump() returns a variable’s data type and value
17
Outputting a String
• Use print or echo to output text or values of variables
<?php
print "Hello World! <br />";
echo "Hello World! <br />"; ?>
• This outputs the text "Hello World!" on two separate lines
– the output is identical
<?php
print ("Hello World! <br />");
echo ("Hello World! <br />"); ?>
• This outputs exactly the same, with parenthesis
• In general, there is no significant difference between echo and
print
18
Text Output
• Be careful when echoing quotes!
• This won't work because of the quotes around specialH5
– echo "<h5 class="specialH5">I love using PHP!</h5>";
• This will work if we ‘escape’ the quotes
– echo "<h5 class=\"specialH5\">I love using
PHP!</h5>";
• Escaping treats the character as a literal rather than having ‘special’
meaning
• The next is ok because we used a single quote
– echo "<h5 class='specialH5'>I love using PHP!</h5>";
19
PHP Assignments and Operators
• Values are assigned using =
– $b = $a copies the value of $a to $b ($a is unchanged)
• Calculations can be performed with +-*/ and %
– Scientific precedence rules apply
• The dot operator . is used for string concatenation
<?php
$str1 = "abc";
$str2 = "def";
print ($str1 . $str2); // gives abcdef
?>
• Can include simple variables inside a string
20
Example Assignments
$a = 120; $a = 1 + 5*3;
$b = $a + 10; echo $a;
echo $b;
$a = 100; $b = 200;
$a = "Alex"; $h = sqrt ($a*$a + $b*$b);
$b = "Coddington"; echo "$a, $b, $h
$c = $a." ".$b; triangle";
echo $c;
echo "Dr $a $b"; $gross_price = 300;
//calc and show inc vat
21
A Longer Example
<html>
<body>
<p>
<?php
$temperature = 5;
$conversionFactorC2K = 273;
print("$temperature °C");
echo " is ";
print($temperature+$conversionFactorC2K."°K");
?>
</p>
</body>
</html>
Output:
22
Arrays
• An array is a special (a single) variable which can hold more than one value
at a time
• In PHP there are three types of array
– Indexed arrays – these are arrays with a numeric index
– Associative arrays – these are arrays with named keys
– Multidimensional arrays – these are arrays which contain one or more arrays
23
Associative Arrays
• Associative arrays are arrays that use named keys that you
assign to them
• There are two ways to create an associative array
– $age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");
– $age['Peter'] = "35"; $age['Ben'] = "37"; $age['Joe']
= "43";
• The named keys can then be used in a script
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
24
Associative Arrays
• Example
<p>
<?php
$phone['mark']='3497';
$phone['john']='3584';
25
Array Size is not Static
• The size of an array is not defined when you
create it (in fact you usually don't say
anything about the size)
26
Predefined Variables
27
Form Processing
• PHP is often used to process data submitted by
the end-user
• Usually this is input to a Web form and submitted
by the browser to the server
• HTML supports many form fields and allows the
page designer to specify the name of the server-
side program that will process the form data
– The program is named in the form action attribute
28
Getting Client Data
• $_POST
– An associative array of variables passed to
the current script via the HTTP POST method.
Similarly $_GET for GET
<?php
echo "Hello ".$_POST["username"];
?>
29
Example continued
<form action="nameandemail2.php" method="post">
Name: <input type="text" name="username"><br>
Email: <input type="text" name="email"><br>
<input type="submit" name="submit" value="Submit">
</form>
<html><body><p>
<?php
echo "Name: ".$_POST['username']."<br>";
echo "Email: ".$_POST['email'];
?>
</p></body></html>
Output:
30
Conditional Expressions
• E.g. if it is going to rain take umbrella
– if / else / elseif are used
if ($mynumber == 10) {
// do this;
}
elseif ($mynumber == 11) {
// do this;
}
else {
// do something else;
}
31
Conditional Example
if (condition) {
…
} else {
…
}
32
Conditional Example 2
• Government introducing wealthy tax
reduction on luxury items to kick start
sales. Anything £1000 or over now only
10% VAT. Calculate $price_vat from $price
33
Switch Statement Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
34
Looping in PHP
• Similar constructs for looping (iteration) are
available in PHP
– for and foreach loops
– while and do…while loops
• Examples
– while tank not full add more petrol
– put three cups of sugar in the coffee
– show the name of each employee
35
For Loops
• for syntax
– for (start_assignment; cont_conditional;
change_assignment) {}
for ($i=0; $i<10; $i++) {
// do this 10 times
}
• foreach syntax
– foreach ( array_variable as value_variable ) {}
– foreach ( array_variable as key_variable =>
value_variable ) {}
36
Sample For
• Output 8 times table
37
Sample Foreach
• e.g.:
<p>
<?php
$phone['mark']='3497';
$phone['ian']='3098';
38
While Loops
• while syntax
– while (cont_conditional) { }
"
while ($i < 10) {
// do this until $i < 10 is false;
}
• do … while syntax:
– do { } while (cont_conditional);
do {
// do this until $i < 10 is false;
}
while ($i < 10);
39
Functions
• A function is a block of statements that can
be used many times within a program
• A function will be executed by a call to the
function
• PHP has a large number of built-in functions
– Functions for arrays, strings, calendar, date,
MySQLi, etc
• You can also create your own functions
40
Functions
• You may define your own PHP functions
<?php
function sayhello ($name) {
echo "Hello $name";
}
sayhello("Satnam");
?>
Output:
41
Return Values
• Can return any type
<?php
function square ($num) {
return $num * $num;
}
echo square(4);
echo "<br/>";
echo square(10)+1;
?>
Output:
42
Parameters – normally by value
<?php
function addNothing($string) {
$string = $string . 'with a cherry on top.';
}
$dessert = 'Ice cream ';
addNothing($dessert);
echo $dessert;
?>
Output:
43
Variable Scope
• The scope of a variable is the part of the
script where the variable can be used
– A variable declared outside a function has global
scope and can only be accessed outside a
function
– You can use the global keyword to access a
global variable within a function
– A variable within a function has local scope and
can only be accessed within that function or loop
44
Global Scope
<?php
$x = 1;
function test()
{
echo $x;
}
test();
?>
45
Using the global keyword
<?php
$x = 1;
$y = 2;
function sum()
{
global $x, $y;
$y = $x + $y;
}
sum();
echo $y;
?>
46
Local Scope
<?php
function displayOne()
{
$x = 1;
echo "<p>The value of x is $x.</p>";
}
displayOne();
echo "<p>The value of x is $x.</p>";
?>
47
The static keyword
• Normally, when a function finishes executing, all of its variables are deleted – the
static keyword allows you to prevent this
<?php
function addOne()
{
static $x = 0;
echo "<p>$x</p>";
$x++;
}
addOne();
addOne();
addOne();
?>
48
Form Handling – isset() function (1)
<form action="handler.php" method = "get">
Day: <input type="checkbox" name="days[]" value= "Saturday">Saturday
<input type="checkbox" name="days[]" value= "Sunday">Sunday<br>
<input type="submit”>
</form>
if (isset($_GET["days"])) {
$weekend=$_GET["days"];
foreach ($weekend as $day)
{ echo ($day." ");}}
49
Form Handling – implode() function
<form action="handler.php" method = "get">
Days: <input type="checkbox" name="days[]" value= "Saturday">Saturday
<input type="checkbox" name="days[]" value= "Sunday">Sunday<br>
<input type="submit”>
</form>
• The file handler.php can include the function isset() and implode()
if (isset($_GET["days"])) {
$weekend=$_GET["days"];
$separatedweekend = implode("; ", $weekend);
$weekendlist = "You are available on: ".$separatedweekend .".";}
echo $weekendlist;
50
Getting help
• http://www.w3schools.com/php/
51