PHP Programming Training
PHP Programming Training
Web Development
REDITA, Jay-R R.
Required Output
At the end of the course, student should be able to develop one of the
following web applications…
– Instructor’s Web Portal
• student’s registration
– School’s Online Registration
– Simulation of an Online Shopping
REDITA, Jay-R R.
Pre-Requisites
• Basic knowledge on the following:
– Hypertext Mark-Up Language (HTML)
– JavaScript
– Cascading Style Sheets (CSS)
– C/C++ Language
REDITA, Jay-R R.
What is PHP?
• PHP is a simple yet powerful language designed for creating HTML
content.
• A server-side scripting language designed to create dynamic web
content. To generate HTML, you need the PHP parser and a web
server to send the documents.
• PHP runs on all major operating systems, from Unix variants
including Linux, FreeBSD, and Solaris to such diverse platforms as
Windows and Mac OS X. It can be used with all leading web
servers, including Apache, Microsoft IIS, and the Netscape/iPlanet
servers.
• One of PHP's most significant features is its wide-ranging support
for databases. PHP supports all major databases (including MySQL,
PostgreSQL, Oracle, Sybase, and ODBC-compliant databases),
and even many obscure ones. With PHP, creating web pages with
dynamic content from a database is remarkably simple.
REDITA, Jay-R R.
Embedding PHP in Web Pages
Although it is possible to write and run standalone PHP
programs, most PHP code is embedded in HTML or XML files. This
is, after all, why it was created in the first place. Processing such
documents involves replacing each chunk of PHP source code with
the output it produces when executed.
REDITA, Jay-R R.
Beginning & Ending Block of a PHP Code
REDITA, Jay-R R.
Display Function
Function Example
echo echo 'Hello World';
echo ('Hello World');
echo "Hello World";
echo ("Hello World");
REDITA, Jay-R R.
Case Sensitivity
The names of user-defined classes and functions, as well
as built-in constructs and keywords such as echo, while, class,
etc., are not case-insensitive. Thus, these three lines are
equivalent:
REDITA, Jay-R R.
Statements & Semicolon
A statement is a collection of PHP code that does something.
It can be as simple as a variable assignment or as complicated as a
loop with multiple exit points. Here is a small sample of PHP
statements, including function calls, assignment, and an if test:
REDITA, Jay-R R.
Statements & Semicolon
PHP uses semicolons to separate simple statements. A
compound statement that uses curly braces to mark a block of code,
such as a conditional test or loop, does not need a semicolon after a
closing brace. Unlike in other languages, in PHP the semicolon before
the closing brace is not optional:
<?php
if ($a == $b) {
echo 'Rhyme? And Reason?';
}
echo 'Hello, world'
?>
REDITA, Jay-R R.
Whitespace and Line Breaks
In general, whitespace doesn't matter in a PHP program. You
can spread a statement across any number of lines, or lump a bunch of
statements together on a single line. For example, this statement:
raise_prices (
$inventory ,
$inflation ,
$cola,
$greed
);
REDITA, Jay-R R.
Comments
• C++ Comment
When PHP encounters two slash characters (//) within the
code, everything from the slashes to the end of the line or the end of the
section of code, whichever comes first, is considered a comment. This
method of commenting is derived from C++. The result is the same as
the shell comment style.
REDITA, Jay-R R.
Comments
• C Comment
While shell- and C++-style comments are useful for annotating
code or making short notes, longer comments require a different style.
As such, PHP supports block comments, whose syntax comes from
the C programming language. When PHP encounters a slash followed
by an asterisk (/*), everything after that until it encounters an asterisk
followed by a slash (*/) is considered a comment.
REDITA, Jay-R R.
Create a php script the will display your
personal information. Format the page so
that it would be nicer.
REDITA, Jay-R R.
Data Types
• PHP provides eight types of values, or data
types. Four are scalar (single-value) types:
integers,
integers floating-point numbers,
numbers strings,
strings and
booleans.
booleans Two are compound (collection) types:
arrays and objects.
objects The remaining two are
special types: resource and NULL.
NULL
REDITA, Jay-R R.
Data Type: Integer
• Integers are whole numbers, like 1, 12, and 256. The range of
acceptable values varies according to the details of your platform
but typically extends from -2,147,483,648 to +2,147,483,647.
REDITA, Jay-R R.
Data Type: Integer
• Octal numbers consist of a leading 0 and a sequence of digits from
0 to 7. Like decimal numbers, octal numbers can be prefixed with a
plus or minus. Here are some example octal values and their
equivalent decimal values:
0755 // decimal 493
+010 // decimal 8
• Hexadecimal values begin with 0x, followed by a sequence of digits
(0-9) or letters (A-F). The letters can be upper- or lowercase but are
usually written in capitals. Like decimal and octal values, you can
include a sign in hexadecimal numbers:
0xFF // decimal 255
0x10 // decimal 16
-0xDAD1 // decimal -56017
• Use the is_int() function to test whether a value is an integer
REDITA, Jay-R R.
Data Type: Floating-point
• Floating-point numbers (often referred to as real numbers) represent
numeric values with decimal digits. Like integers, their limits depend
on your machine's details. PHP floating-point numbers are
equivalent to the range of the double data type of your C compiler.
Usually, this allows numbers between 1.7E-308 and 1.7E+308 with
15 digits of accuracy.
• PHP recognizes floating-point numbers written in two different
formats. There's the one we all use every day:
3.14 0.017 -7.1
• PHP also recognizes numbers in scientific notation:
0.314E1 // 0.314*101, or 3.14
17.0E-3 // 17.0*10-3, or 0.017
REDITA, Jay-R R.
Data Type: String
• Double quotes also support a variety of string escapes
Escape Sequence Character Represented
\” Double quotes
\n Newline
\r Carriage return
\t Tab
\\ Backslash
\$ Dollar sign
\{ Left brace
\} Right brace
\[ Left bracket
\] Right bracket
\0 through \777 ASCII character represented by octal value
\x0 through \xFF ASCII character represented by hex value
REDITA, Jay-R R.
Data Type: String
• A single-quoted string only recognizes \\ to get a literal
backslash and \' to get a literal single quote.
REDITA, Jay-R R.
Data Type: Boolean
• A boolean value represents a "truth value"—it says
whether something is true or not. Like most programming
languages, PHP defines some values as true and others
as false.
• In PHP, the following values are false:
– The keyword false
– The integer 0
– The floating-point value 0.0
– The empty string ("") and the string "0"
– An array with zero elements
– An object with no values or functions
– The NULL value
REDITA, Jay-R R.
Data Type: Boolean
• PHP provides true and false keywords for clarity:
– $x = 5; // $x has a true value
– $x = true; // clearer way to write it
– $y = ""; // $y has a false value
– $y = false; // clearer way to write it
REDITA, Jay-R R.
Data Type: Array
• An array holds a group of values, which you can identify
by position (a number, with zero being the first position)
or some identifying name (a string):
$person[0] = "Edison";
$person[1] = "Wankel";
$person[2] = "Crapper";
REDITA, Jay-R R.
The array() construct creates an array:
$person = array(
'Edison',
'Wankel',
'Crapper'
);
$creator = array(
'Light bulb' => 'Edison',
'Rotary Engine' => 'Wankel',
'Toilet' => 'Crapper'
);
REDITA, Jay-R R.
There are several ways to loop across arrays, but the most common is
a foreach loop:
Hello, Edison
Hello, Wankel
Hello, Crapper
sort($person);
// $person is now array('Crapper', 'Edison', 'Wankel')
asort($creator);
/* $creator is now
array( 'Toilet' => 'Crapper',
'Light bulb' => 'Edison',
'Rotary Engine' => 'Wankel‘
);
/*
REDITA, Jay-R R.
Data Type: Object
• PHP supports object-oriented programming (OOP). OOP promotes
clean modular design, simplifies debugging and maintenance, and
assists with code reuse.
class Person {
var $name = '';
function name ($newname = NULL) {
if (! is_null($newname)) {
$this->name = $newname;
}
return $this->name;
}
}
REDITA, Jay-R R.
• Once a class is defined, any number of objects can be made from
it with the new keyword, and the properties and methods can be
accessed with the -> construct:
Hello, Edison
Look out below Crapper
REDITA, Jay-R R.
• You can use PHP's built-in function gettype() to acquire the type
of any variable. If you place a variable between the parentheses of
the function call, gettype() returns a string representing the
relevant type.
<?php
$testing; // declare without assigning
echo gettype($testing)."<br/>"; // NULL
$testing = 5;
echo gettype($testing)."<br/>"; // integer
$testing = "five";
echo gettype($testing)."<br/>"; // string
$testing = 5.0;
echo gettype($testing)."<br/>"; // double
$testing = true;
echo gettype($testing)."<br/>"; // boolean
?>
REDITA, Jay-R R.
• PHP provides the function settype() to change the type of a
variable. To use settype(), you must place the variable to change
(and the type to change it to) between the parentheses and
separate them by commas.
<?php
$undecided = 3.14;
echo gettype($undecided); // double
echo " -- $undecided<br/>"; // 3.14
settype($undecided, string);
echo gettype($undecided); // string
echo " -- $undecided<br />"; // 3.14
settype($undecided, int);
echo gettype($undecided); // integer
echo " -- $undecided<br />"; // 3
settype($undecided, double);
echo gettype($undecided); // double
echo " -- $undecided<br />"; // 3.0
settype($undecided, bool);
echo gettype($undecided); // boolean
echo " -- $undecided<br />"; // 1
?>
REDITA, Jay-R R.
Variables
• Variables in PHP are identifiers prefixed with a dollar
sign ($).
For example:
$name
$Age
$_debugging
$MAXIMUM_IMPACT
REDITA, Jay-R R.
• A variable may hold a value of any type. There is no
compile- or runtime type checking on variables.
$what = "Fred";
$what = 35;
$what = array('Fred', '35', 'Wilma');
REDITA, Jay-R R.
Variable Scope
• The scope of a variable, which is controlled by the
location of the variable's declaration, determines those
parts of the program that can access it.
REDITA, Jay-R R.
Local Scope
A variable declared in a function is local to that function. That is, it is
visible only to code in that function, it is not accessible outside the
function. In addition, by default, variables defined outside a function
(called global variables) are not accessible inside the function. For
example, here's a function that updates a local variable instead of a
global variable:
function update_counter ( ) {
$counter++;
}
$counter = 10;
update_counter( );
echo $counter;
function update_counter ( ) {
global $counter;
$counter++;
}
$counter = 10;
update_counter( );
echo $counter;
REDITA, Jay-R R.
Global Scope
A more cumbersome way to update the global variable is to use
PHP's $GLOBALS array instead of accessing the variable directly:
function update_counter ( ) {
$GLOBALS[counter]++;
}
$counter = 10;
update_counter( );
echo $counter;
REDITA, Jay-R R.
Static Scope
A static variable retains its value between calls to a function but is
visible only within that function. You declare a variable static with the
static keyword. For example:
function update_counter ( ) {
static $counter = 0;
$counter++;
echo "Static counter is now $counter";
echo "<br>";
}
$counter = 10;
update_counter( );
update_counter( );
echo "Global counter is $counter<br>";
greet("Janet");
Function parameters are local, meaning that they are available only
inside their functions. In this case, $name is inaccessible from outside
greet( ).
REDITA, Jay-R R.
About variables…
To see if a variable has been set to something, even the empty string,
use isset():
$name = "Fred";
unset($name); // $name is NULL
REDITA, Jay-R R.
Operators
Arithmetic Operators
Operator Name Example Result
+ Addition 10 + 3 13
- Subtraction 10 – 3 7
/ Division 10 / 3 3.3333333333333
* Multiplication 10 * 3 30
% Modulus 10 % 3 1
Assignment w/ Operators
Operator Example Equivalent to
+= $x += 5 $x = $x + 5
-= $x -= 5 $x = $x – 5
/= $x /= 5 $x = $x / 5
*= $x *= 5 $x = $x * 5
.= $x .= 'test' $x = $x.'test'
REDITA, Jay-R R.
Operators
Comparison Operators
Operator Name Example Result
== Equality 10.0 == 10 True
=== Identical 10.0 === 10 False
!= or <> Inequality 10.0 != 11 True
!== Not Identical 10.0 !== 10 True
> Greater than 10 > 3 True
< Less than 10 < 3 False
>= Greater than or equal to 10 >= 10 True
<= Less than or equal to 10 <= 10 True
Logical Operators
Operator Name Example Result
&& , and Logical AND (10 > 3) && ( 3 > 5) False
|| , or Logical OR (10 > 3) || ( 3 > 5) True
! Logical Negation ! (10 > 3) False
REDITA, Jay-R R.
Q&A
Q1: Why can it be useful to know the type of data a variable holds?
A1: Often the data type of a variable constrains what you can do with it. You
might want to ensure that a variable contains an integer or a double before
using it in a mathematical calculation, for example.
A2: Your goal should always be to make your code easy to both read and
understand. A variable such as $ab 123245 tells you nothing about its role
in your script and invites typos. Keep your variable names short and
descriptive. A variable named $f is unlikely to mean much to you when you
return to your code after a month or so. A variable named $filename, on the
other hand, should make more sense.
REDITA, Jay-R R.
Workshop
1: Which of the following variable names is not valid?
$a_value_submitted_by_a_user
$666666xyz
$xyz666666
$_____counter_____
$the first
$file-name
REDITA, Jay-R R.
Exercises
1. Create a script that contains at least five different variables.
Populate them with values of different data types and use the
gettype() function to print each type to the browser.
REDITA, Jay-R R.
Flow Control Statements
• PHP supports a number of traditional programming
constructs for controlling the flow of execution of a
program.
REDITA, Jay-R R.
If Statement
• The if statement checks the truthfulness of an expression and, if the
expression is true, evaluates a statement. An if statement looks like:
if (expression)
statement
if (expression)
statement
else
statement
REDITA, Jay-R R.
If Statement
• For example:
if ($user_validated)
echo "Welcome!";
else
echo "Access Forbidden!";
if ($user_validated) {
echo 'Welcome!";
$greeted = 1;
} else {
echo "Access Forbidden!"; exit;
} REDITA, Jay-R R.
If Statement
• PHP provides another syntax for blocks in tests and loops. Instead of
enclosing the block of statements in curly braces, end the if line with a
colon (:) and use a specific keyword to end the block (endif, in this
case).
For example:
if ($user_validated) :
echo "Welcome!";
$greeted = 1;
else :
echo "Access Forbidden!";
exit;
endif;
REDITA, Jay-R R.
If Statement
• Because if is a statement, you can chain them:
if ($good)
print('Dandy!');
else
if ($error)
print('Oh, no!');
else
print("I'm ambivalent...");
• Such chains of if statements are common enough that PHP provides an
easier syntax: the elseif statement. For example, the previous code can
be rewritten as:
if ($good)
print('Dandy!');
elseif ($error)
print('Oh, no!');
else
print("I'm ambivalent...");
REDITA, Jay-R R.
Ternary Operator
• The ternary conditional operator (?:) can be used to
shorten simple true/false tests. Take a common situation
such as checking to see if a given variable is true and
printing something if it is. With a normal if/else
statement, it looks like this:
REDITA, Jay-R R.
Switch Statement
• It often is the case that the value of a single variable may
determine one of a number of different choices (e.g., the
variable holds the username and you want to do
something different for each user).
REDITA, Jay-R R.
• For example, suppose you have the following:
if ($name == 'troy')
// do something
elseif ($name == 'rasmus')
// do something
elseif ($name == 'rick')
// do something
elseif ($name == 'bob')
// do something
switch($name) {
case 'troy': // do something
break;
case 'rasmus': // do something
break;
case 'rick': // do something
break;
case 'bob': // do something
break;
}
REDITA, Jay-R R.
• An alternative syntax can be:
switch($name):
case 'troy':
// do something
break;
case 'rasmus':
// do something
break;
case 'rick':
// do something
break;
case 'bob':
// do something
break;
endswitch;
REDITA, Jay-R R.
Loop Statements
REDITA, Jay-R R.
While Loop
• The simplest form of loop is the while statement:
while (expression)
statement
REDITA, Jay-R R.
• As an example, here's some code that adds the whole numbers
from 1 to 10:
$total = 0; $i = 1;
while ($i <= 10) {
$total += $i;
}
echo 'SUM (1-10) : '.$total;
• The alternative syntax for while has this structure:
while (expr):
statement; ...;
endwhile;
• For example:
$total = 0; $i = 1;
while ($i <= 10):
$total += $i; $i++;
endwhile;
echo 'SUM (1-10) : '.$total;
REDITA, Jay-R R.
• You can prematurely exit a loop with the break keyword. In the
following code, $i never reaches a value of 6, because the loop is
stopped once it reaches 5:
$total = 0;
$i = 1;
while ($i <= 10) {
if ($i == 5) break; // breaks out of the loop
$total += $i;
$i++;
}
echo 'SUM : '.$total;
REDITA, Jay-R R.
Do..While Loop
• PHP also supports a do /while loop, which takes the following form:
• do statement while (expression) Use a do/while loop to ensure that
the loop body is executed at least once:
$total = 0; $i = 1;
do {
$total += $i;
$i++;
} while ($i <= 10);
echo 'SUM (1-10) : '.$total;
• You can use break and continue statements in a do/while statement
just as in a normal while statement. The do/while statement is
sometimes used to break out of a block of code when an error
condition occurs.
REDITA, Jay-R R.
For Loop
• The for statement is similar to the while statement, except it adds
counter initialization and counter manipulation expressions, and is
often shorter and easier to read than the equivalent while loop.
• Here's a while loop that counts from 0 to 9, printing each number:
$counter = 0;
while ($counter < 10) {
echo 'Counter is '.$counter.'<br/>';
$counter++;
}
REDITA, Jay-R R.
For Loop
• The structure of a for statement is:
for (start; condition; increment)
statement
REDITA, Jay-R R.
• This program adds the numbers from 1 to 10 using a for loop:
$total = 0;
for ($i= 1; $i <= 10; $i++) {
$total += $i;
}
echo 'SUM (1-10) : '.$total;
REDITA, Jay-R R.
Foreach
• The foreach statement allows you to iterate over elements in an
array.
REDITA, Jay-R R.
Foreach
• To loop over an array, accessing both key and value, use:
foreach ($array as $key => $value) {
// ...
}
REDITA, Jay-R R.
Example
<?php
$person = array('Edison', 'Wankel', 'Crapper');
$creator = array(
'Light bulb' => 'Edison',
'Rotary Engine' => 'Wankel',
'Toilet' => 'Crapper'
);
REDITA, Jay-R R.
Workshop
1. How would you use an if statement to print the string "Youth
message" to the browser if an integer variable, $age, is between
18 and 35? If $age contains any other value, the string "Generic
message" should be printed to the browser.
2. How would you extend your code in question 1 to print the string
"Child message" if the $age variable is between 1 and 17?
3. How would you create a while statement that prints every odd
number between 1 and 49?
REDITA, Jay-R R.
5. Create a PHP script that will ask user to enter an integer value
only and display all the divisors of the number. Note: Use Form
6. Create a PHP script that will ask user to enter two integer and will
determine the greatest common divisor of the two numbers. Use
Form?
7. Create a PHP script that will ask user to enter an integer value and
will determine if the number is PRIME or NOT?
REDITA, Jay-R R.