HTML Forms and Server Side Scripting - PHP
HTML Forms and Server Side Scripting - PHP
Chapter Two
HTML FORMS AND SERVER
SIDE SCRIPTING
5/18/2024
By:- Abreham G.
Using Operators
2
Mathematical Operators
Arithmetic operators are straightforward—they are just the
normal mathematical operators.
Operator Description
+ Adds two numbers together.
- Subtracts the second number from the first number.
* Multiplies two numbers together.
5/18/2024
Using Operators…
4
5/18/2024
Using Operators…
5
All the increment operators have two effects—they increment and assign a value.
$a=4;
echo ++$a;
The second line uses the prefix increment operator.
First, $a incremented by 1, and second, returns the incremented value.
In this case, $a is incremented to 5 and then the value 5 is returned and printed.
However, if the ++ is after the $a, we are using the postfix increment operator.
This has a different effect.
$a=4;
echo $a++;
In this case, first, the value of $a is returned and printed, and second, it is
incremented.
The value that is printed is 4.
However, the value of $a after this statement is executed is 5.
5/18/2024
Using Operators…
7
5/18/2024
Using Operators…
8
Comparison operators
The comparison operators are used to compare two values.
Expressions using these operators return either true or false
operator name description
== equal True if its arguments are equal to each other, false otherwise
!= not equal False if its arguments are equal to each other, true otherwise
< less than True if the left-hand argument is less than its right-hand argument, but false
otherwise
> greater than True if the left-hand argument is greater than its right-hand argument, but
false otherwise
<= less or equal True if the left-hand argument is less than its right-hand argument or equal to
it, but false otherwise
>= greater or equal True if the left-hand argument is greater than its right- hand argument or
equal to it, but false otherwise
=== identical True if its arguments are equal to each other and of the same type, but false
5/18/2024
otherwise
Using Operators…
9
Example:
<?php
$var = "30";
$num = 30;
if($var == $num)
print "They are equal.<br>";
if($var === $num)
print "They are equal and same data type.<br>";
$var = (int) “30”;
if($var === $num)
print "2. They are equal and same data type.<br>";
?>
Output:
They are equal
5/18/2024
2. They are equal and same data type.
Using Operators…
10
Logical Operators
The logical operators are used to combine the results of logical
conditions.
For example, we might be interested in a case where the value
of a variable is between 0 and 100.
We would need to test the conditions $a >= 0 and $a <=
100, using the AND operator, as follows:
if($a >= 0 && $a <=100)
5/18/2024
Using Operators…
11
operator description
xor Is true if either (but not both) of its arguments are true
! Is true if its single argument (to the right) is false and false if its argument is true
5/18/2024
Using Operators…
12
branching construct.
Its job is to take three expressions and use the truth value of the first
expression to decide which of the other two expressions to return.
The syntax looks like:
test-expression ? yes-expression : no-expression
if Statements
We can use an if statement to make a decision.
You should give the if statement a condition that is evaluated to true or false.
else if Statements
For many of the decisions we make, there are more than two options.
By providing a sequence of conditions, the program can check each until it finds one
that is true.
switch statements
The switch statement works in a similar way to the if
statement
You need to provide a case statement to handle each
value you want to react to and, optionally, a default
case to handle any that you do not provide a specific
case statement.
5/18/2024
Conditional Statements…
17
switch (expression) {
case result1:
//execute this if expression results in result1
break;
case result2:
//execute this if expression results in result2
break;
default:
//execute this if no break statement
//has been encountered
}
5/18/2024
Using Loops
20
for loop
The most basic for loops are based on a counter.
You set the beginning value for the counter, set the ending value, and
set how the counter is incremented/decremented.
The general format is as follows:
Example:
for ($i = 1; $i <= 3; $i++) {
echo “$i. Hello World!<br>”;
}
5/18/2024
You can nest for loops inside of for loops.
Excersice
22
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81
5/18/2024
Using Loops…
23
while loop
One of PHP looping construct is while, which has the following syntax:
while (condition)
{
statement
}
do..while loop
Like a while loop, a do..while loop continues repeating as long
as certain conditions are true.
Unlike while loops, the conditions are tested at the bottom of
the loop.
If the condition is true, the loop repeats.
Exercise
1. Write a while loop that displays prime numbers
between 1 and 100
2. Write a for loop that displays the squared and
cubed value of numbers between 0 and 100.
3. Write a do while loop that calculates the factorial
of a number.
4. Write a loop that gets the factors of a given
number.
5/18/2024
Array
29
5/18/2024
Creating Array
30
Formally
Uses the array() function
array array([item1 [,item2 ... [,itemN]]])
$languages = array ("English", "Gaelic", "Spanish");
$languages = array ("Spain" => "Spanish","Ireland" =>
"Gaelic", "United States" => "English");
5/18/2024
Cont.……
31
range()
The range() function provides an easy way to quickly create
and fill an array consisting of a range of low and high
integer values.
$die = range(0,6);
Same as specifying $die = array(0,1,2,3,4,5,6)
The optional step parameter offers a convenient means for
determining the increment between members of the range.
$even = range(0,20,2);
also be used for character sequences
$letters = range("A","F");
5/18/2024
Outputting Array
32
5/18/2024
Adding and Removing array elements
33
5/18/2024
Cont.…..
34
array_shift()
The array_shift() function is similar to array_pop(), except
that it returns the first array item found on the target_array
rather than the last.
$states = array("Ohio","New York","California","Texas");
$state = array_shift($states);
array_unshift()
The array_unshift() function is similar to array_push(), except
that it adds elements to the front of the array rather than to
the end.
$states = array("Ohio","New York");
array_unshift($states,"California","Texas");
5/18/2024
Cont.….
35
array_pad()
The array_pad() function modifies the target array,
increasing its size to the length specified by length.
$states = array("Alaska","Hawaii");
$states = array_pad($states,4,"New colony?");
5/18/2024
Locating array elements
36
Array_keys()
returns an array consisting of all keys located in the
array target_array.
E.g show the keys using print_r()
array_key_exists()
boolean array_key_exists(mixed key, array
target_array).
returns TRUE if the supplied key is found in the array
target_array, and returns FALSE otherwise.
5/18/2024
Cont.….
37
array_values()
The array_values() function returns all values located in the array
target_array, automatically providing numeric indexes for the
returned array.
array_search()
searches the array haystack for the value needle, returning its
key if located, and FALSE otherwise.
mixed array_search(mixed needle, array haystack [, boolean strict])
Traversing array
Using foreach loop
foreach ($colors as $value)
{
echo "$value <br>";
}
5/18/2024
Determine Array size and uniqueness
38
count()
integer count(input_array)
returns the total number of values found in the input_array.
array_count_values()
returns an array consisting of associative key/value pairs.
Each key represents a value found in the input_array, and its
corresponding value denotes the frequency of that key’s
appearance (as a value) in the input_array.
E.g. Array ( [Ohio] => 2 [Iowa] => 2 [Arizona] => 1 )
5/18/2024
Sorting Array
39
sort()
sorts the target_array, ordering elements from lowest to
highest value.
rsort()
is identical to sort(), except that it sorts array items in
reverse (descending) order.
asort()
is identical to sort(), sorting the target_array in
ascending order, except that the key/value
correspondence is maintained.
5/18/2024
Cont.…
40
ksort()
sorts the input array by its keys, returning TRUE on
success and FALSE otherwise.
krsort()
operates identically to ksort(), sorting by key, except
that it sorts in reverse (descending) order.
5/18/2024
Merging, Slicing, splicing and
41
Dissecting
array_combine()
array array_combine(array keys, array values)
produces a new array consisting of keys residing in the
input parameter array keys, and corresponding values
found in the input parameter array values.
both input arrays must be of equal size, and that
neither can be empty.
E.g.$abbreviations = array("AL","AK","AZ","AR");
$states = array("Alabama","Alaska","Arizona","Arkansas");
$stateMap = array_combine($abbreviations,$states);
5/18/2024
Cont.…….
42
array_merge()
appends arrays together, returning a single, unified
array.
If an input array contains a string key that already
exists in the resulting array, that key/value pair will
overwrite the previously existing entry.
array_slice()
array array_slice(array input_array, int offset [, int
length])
returns the section of input_array, starting at the key
offset and ending at position offset + length.
5/18/2024
Cont.……
43
array_splice()
array array_splice(array input, int offset [, int length [,
array replacement]])
removes all elements of an array, starting at offset and
ending at position offset + length, and will return those
removed elements in the form of an array.
5/18/2024
Cont.….
44
array_intersect()
The array_intersect() function returns a key-preserved
array consisting only of those values present in
input_array1 that are also present in each of the other
input arrays.
array array_intersect(array input_array1, array
input_array2 [, array...])
Note that array_intersect() considers two items to be
equal only if they also share the same datatype.
5/18/2024
Cont….
45
array_diff()
array array_diff(array input_array1, array
input_array2 [, array...])
returns those values located in input_array1 that are
not located in any of the other input arrays.
5/18/2024
Function
46
5/18/2024
Creating Function
47
5/18/2024
Passing Arguments
48
Passing by value
The original variable’s value will not be changed even
if the recipient variable value is changed.
<?php
function adder($str2)
{
$str2 .= 'Call By Value';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
5/18/2024
Passing Arguments
49
Passing by reference
is done by appending an ampersand to the front of the
parameter(s).
It changes the original variable's value.
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'This is ';
adder($str);
echo $str;
?>
5/18/2024
PHP Variable Length Argument
Function
50
PHP supports variable length argument function. It means you can pass 0, 1 or n number of
arguments in function. To do so, you need to use 3 ellipses (dots) before the argument name.
The 3 dot concept is implemented for variable length argument since PHP 5.6.
<?php
function add(...$numbers) {
$sum = 0;
foreach ($numbers as $n) {
$sum += $n;
}
return $sum;
}
5/18/2024
Default and Optional arguments
51
5/18/2024
•
Recursive Function
52
display(1);
?>
5/18/2024
Functions in PHP…
53
Variable Scope
A variable declared within a function remains local to that function.
output:
inside the function, $var = contents
outside the function, $var = contents
5/18/2024
Functions in PHP…
56
A second way to access variables from the global scope is to use the
special PHP-defined $GLOBALS array.
The previous example can be rewritten as:
<?php
$a = 1;
$b = 2;
function Sum()
{
$GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"];
}
Sum();
echo $b;
?>
5/18/2024
Functions in PHP…
58
Exercise
1. Write a function that accepts a number and returns
the squared and cubed value of the number.
2. Write a function that accepts a number as parameter
and then calculates the factorial of the number and
return it.
3. Write a function that accepts price of a commodity
and then calculates VAT tax(15%) and return it.
4. Write a function that calculates compound interest on
principal.
5/18/2024
Class
59
It is a data type.
Collection of objects.
It is composed of fields and methods.
E.g. class classname
{
// Field declarations defined here
// Method declarations defined here
}
5/18/2024
Objects
60
Is an instance of a class.
The practice of creating objects based on
predefined classes is often referred to as class
instantiation.
Objects are created using the new keyword.
E.g.
$employee = new Staff();
5/18/2024
Invoking Fields and Method
61
5/18/2024
Cont.…..
62
Field Scopes
PHP supports five class field scopes: public, private,
protected, final, and static.
Public
Public fields can then be manipulated and accessed directly by a
corresponding object.
Private
Private fields are only accessible from within the class in which
they are defined.
Protected
Protected fields are also made available to inherited classes for
access and manipulation, a trait not shared by private fields.
final
5/18/2024
Methods
63
{
/* Function body goes here */
}
$object->method_name();
5/18/2024
Constructors
64
5/18/2024
Static Class Members
65
Autoloading Objects
require_once("classes/Books.class.php");
5/18/2024
Form Handling
66
5/18/2024
PHP Get Form
67
5/18/2024
68
File: welcome.php
<?php
$name=$_GET["name"];//receiving name field value in $
name variable
echo "Welcome, $name";
?>
5/18/2024
PHP Post Form
69
5/18/2024
70
File: form1.html
<form action="login.php" method="post">
<table>
<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
<tr><td>Password:</td><td> <input type="password" name="password"/></td>
</tr>
<tr><td colspan="2"><input type="submit" value="login"/> </td></tr>
</table>
</form>
5/18/2024
71
File: login.php
<?php
$name=$_POST["name"];//receiving name field value in $name v
ariable
$password=$_POST["password"];//receiving password field valu
e in $password variable
echo "Welcome: $name, your password is: $password";
?>
5/18/2024
GET vs. POST
72
Both GET and POST create an array (e.g. array( key =>
value, key2 => value2, key3 => value3, ...)). This array
holds key/value pairs, where keys are the names of the form
controls and values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST.
These are super globals, which means that they are always
accessible, regardless of scope - and you can access them
from any function, class or file without having to do
anything special.
$_GET is an array of variables passed to the current script
via the URL parameters.
$_POST is an array of variables passed to the current script
via the HTTP POST method.
5/18/2024
When to use GET?
73
5/18/2024
When to use POST?
74
Information sent from a form with the POST method is
invisible to others (all names/values are embedded within
the body of the HTTP request) and has no limits on the
amount of information to send.
Moreover POST supports advanced functionality such as
support for multi-part binary input while uploading files to
server.
However, because the variables are not displayed in the
URL, it is not possible to bookmark the page.
Generally we can use post when there is
Sensitive information
Large amount of data
It Can not bookmark
Advantage
Code Reusability: By the help of include and require
construct, we can reuse HTML code or PHP script in many
PHP scripts.
5/18/2024
Forms - Validate
76
5/18/2024
Forms - Validate
77
5/18/2024
Forms - Validate
78
5/18/2024
Forms - Validate
79
5/18/2024
PHP include example
80
5/18/2024
PHP require
81
File: require1.php
<?php require("menu.html"); ?>
<h1>This is Main Page</h1>
5/18/2024
PHP include vs PHP require
82
5/18/2024
Be the digger of
Question
Comment
Thank you!