0% found this document useful (0 votes)
27 views

Applications Development & Emerging Technologies

PHP was originally created by Rasmus Lerdorf in 1994 and has since evolved significantly. It is a popular open source server-side scripting language that is commonly embedded in HTML. Some key aspects of PHP include its practicality, power, and ability to easily integrate databases. Standard PHP code is enclosed by opening and closing tags. Variables must begin with a $ symbol and datatypes include scalars like integers and strings, as well as compounds like arrays and objects. Common output functions include echo, print, and printf. Operators allow performing actions in expressions and have defined precedence and associativity rules. Control structures help direct program flow.

Uploaded by

Camille
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Applications Development & Emerging Technologies

PHP was originally created by Rasmus Lerdorf in 1994 and has since evolved significantly. It is a popular open source server-side scripting language that is commonly embedded in HTML. Some key aspects of PHP include its practicality, power, and ability to easily integrate databases. Standard PHP code is enclosed by opening and closing tags. Variables must begin with a $ symbol and datatypes include scalars like integers and strings, as well as compounds like arrays and objects. Common output functions include echo, print, and printf. Operators allow performing actions in expressions and have defined precedence and associativity rules. Control structures help direct program flow.

Uploaded by

Camille
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

CCS0043LL

Subtopic 1: Introduction to PHP


INTRODUCTION TO PHP WEB PROGRAMMING
Objectives
- To understand the history of PHP
- To know the advantages of PHP as a server-side scripting language
- To know what are the software's needed in developing web application using PHP.
- To run PHP application on a web browser.
- To know the basic syntax of PHP for outputting to browser.
- To know the datatypes that are available on PHP and on how these datatypes are being
used.
- To know some predefined type function for data manipulation.
- To know the proper casting values of a given variables.

HISTORY
- 1994/1995 (PHP 1.0)
o Developed by Rasmus Lerdorf
o To know how many visitors were re adding his online resume based on PERL/CGI script
o Personal Home Page (PHP)
- 1997 (PHP 2.0)
o PHP is based on C rather than PERL
o Personal Home Page/Form Interpreter
- 1998 (PHP 3.0)
o 50,000 users were using PHP to enhance their Web pages
o Developers joined Lerdorf
- 1999 (PHP 4.0)
o With core developers Zeev Suraski and Andi Gutmans
o PHP makes the most popular scripting language with more than one million user base by
Netcraff
o Hundreds of functions being added
o Dubbed the Zend scripting engine
- May 22, 2000 (PHP 4.0)
o PHP: Hypertext Preprocessor (recursive acronym)
o 3.6 million domain PHP installed
o Enterprise development
▪ Improved resource handling (scalability)
▪ Object-oriented support (Classes and Objects)
▪ Native session-handling support (session)
▪ Encryption (encryption algorithms)
▪ ISAPI Support (for IIS)
▪ Native COM/DOM (Windows applications)
▪ Native Java Support: (binding to java objects)
▪ PERL Compatible Regular Expressions
o New features, power, and scalability
HISTORY (cont.)
- PHP 5 (July 13, 2004)
o Vastly improved object-oriented capabilities: OOP improvement
o Try/catch exception handling
o Improved XML and Web Services support (Simple XML Support, using SOAP)
o Native support for SQLite
o Installed on 19 million domains
o 54 percent on all Apache module
- PHP 6 (2007 not yet released)
o Unicode Support (Native Unicode support for multilingual applications
o Security improvements
o New language features and constructs (64-bit type integer, foreach looping)
- PHP Key categories
o Practicality
▪ PHP is a loosely type language (no explicitly create, typecast, or destroy a
variable)
o Power
▪ More libraries and thousands of functions
o Possibility
▪ Native support is offered for more than 25 database products, including Adabas
D, dBase, Empress, FilePro, FrontBase, Hyperwave, IBM DB2, Informix, Ingres,
InterBase, mSQL, Microsoft SQL Server, MySQL, Oracle, Ovrimos, PostgreSQL,
Solid, Sybase, Unix dbm, and Velocis.
▪ Both structured and Object Oriented approach
o Price
▪ Free of charge

WEB ARCHITECTURE
SOFTWARE REQUIREMENTS – OPERATING SYSTEM: LINUX

SOFTWARE REQUIREMENTS – OPERATING SYSTEM: WINDOWS

SOFTWARE REQUIREMENTS – OPERATING SYSTEM: MAC


SOFTWARE REQUIREMENTS – INTERNET BROWSERS

SOFTWARE REQUIREMENTS – WEB SERVER

SOFTWARE REQUIREMENTS – SERVER-SIDE SCRIPTING LANGUAGE

SOFTWARE REQUIREMENTS – DATABASE


SOFTWARE REQUIREMENTS – CODE EDITOR

SOFTWARE REQUIREMENTS – OTHER

Subtopic 2: PHP Environment


Running PHP Scripts
XAMPP
1. Download XAMPP: http://www.apachefriends.org/en/xampp.html
2. Install XAMPP
3. Run XAMPP Control
a. c:\xampp (by default)
b. Start the Apache and MySQL(for database) Service
4. Create a folder under c:\xampp\htdocs\ (by default)
Note: All php files must be save on that folder
5. Test PHP script sample file.
a. Open some internet browser
b. Type localhost/[folder name] (by default)
c. Select file from the directory list
RUNNING PHP SCRIPTS

Opening tag for php script Statement terminator

Closing tag for php script echo – is a language construct that use to output one or more string.
print – is a function also use for outputting strings.

PHP COMMENTS

PHP Variables
- Variables are used as a container for values that can be used and manipulate PHP scripts.
- Variables in PHP must begin with a $ symbol.
- Variable might contain a string, numbers, arrays and objects.
- Setting the identifier for a variable must follow some rules.
1. First character can be ‘_’ or a letter.
2. It can only contain alpha-numeric characters and underscore (a-z,A-Z,0-9,_).
3. Don’t use white space in naming a variable.
- Variables in PHP is not explicitly declared
- Variables are case sensitive
- Example
$age, $firstName, $totalSalary, $_myValue,
$str1, $tmp01

Using ‘ ‘ (pair single quote), “ “ (pair double quotes) and . (dot character) PHP
1. Strings inside the ‘ and ‘ are interpreted as literal strings
• To display a ‘ character (single quote) as string use the escape character \ (backslash).
2. Strings inside the “ and “ are interpreted as literal strings with some exceptions
• $ inside “ and “ are interpreted as variables thus it will display the value rather than the
string that starts with $.
• To display the string that starts with $ and to display the double quote as string use the
escape character \(backslash).
3. To concatenate string values use the . (dot or period) character thus “abc“.”def” yields to a
value “abcdef”
Using ‘ ‘ (pair single quote), “ “ (pair double quotes) and . (dot character) PHP
EXAMPLE: OUTPUT:

OUTPUTTING DATA
- echo syntax
o void echo(string argument1[,…string argumentN]
- print syntax
o int print(argument)
- printf syntax
o boolean printf(string format [, mixed args])
EXAMPLE: OUTPUT:

COMMONLY USED TYPE SPECIFIERS FOR PRINTF FUNCTION


PHP DATATYPES
- Datatypes
o is the generic name assigned to any data sharing a common set of characteristics.
- Scalar Datatypes
o Capable of containing a single item of information (Boolean, Integer, Float (float,
double or real numbers), String)
o EXAMPLE:

- Compound Datatypes
o allow for multiple items of the same type to be aggregated under a single
representative entity. (Array and Objects)
o EXAMPLE 1:

o EXAMPLE 2:
PHP TYPE CASTING OPERATORS

EXAMPLE:

PHP TYPE JUGGLING


EXAMPLE:
PREDEFINED TYPE FUNCTIONS
- gettype() function
o returns the type of the variable. Possible return values are integer, double, boolean,
string, array, object, resource, unknown types.
o prototype: string gettype(mixed var)
- settype() function
o converts a given variable to a specific type.
o prototype: boolean settype(mixed var, string type)

PREDEFINED TYPE IDENTIFIER FUNCTIONS


- is_array(), is_bool(), is_float(), is_integer(),
- is_null(), is_numeric(), is_object(), is_resource(),
- is_scalar(), and is_string()

TYPE FUNCTIONS
EXAMPLE:

SUMMARY:
- PHP was developed originally by Rasmus Lerdorf
- Seev Suraski and Andi Gutsman were the one who contribute most in PHP development.
- PHP key categories are practicality, power, possibility, and price.
- PHP is a embedded language that is commonly embedded on HTML
- PHP is a server-side scripting language that runs its application on a Web server.
- Much of the PHP syntax were derive from C programming Language.
- You can integrate database easily in PHP.
- Standard PHP script are enclosed by <?php and ?> tags.
- Each statement in PHP must be terminated with a semi-colon(;).
- All variable in PHP must have a dollar ($) character before its identifier
- PHP variables are not explicitly declared.
- You can use echo, print, or printf function for outputting strings to internet browser.
- You can enclosed string using a pair of single quote or pair of double quote.
SUMMARY: (cont.)
- String inside a pair of single quote interpreted as literal except for the single quote itself.
- String inside a pair of double quote interpreted as literal with some exception like using dollar
character.
- To explicitly display the character on the internet browser use backslash (\) character like \$,
\’, \” and etc.
- Datatypes in PHP can be categorized as scalar or compound datatypes.
- You can explicitly change the type of a variable in PHP.
- PHP support some predefined type function that can be used in manipulating type variables

Subtopic 1: PHP Operators


OPERATORS
- An operator is a symbol that specifies a particular action in an expression

Operator Precedence, Associativity, and Purpose


OPERATOR PRECEDENCE
- is a characteristic of operators that determines the order in which they evaluate the operands
surrounding them.

OPERATOR ASSOCIATIVITY
- is a characteristic of an operator specifies how operations of the same precedence are
evaluated as they are executed.

ARITHMETIC OPERATOR

ASSIGNMENT OPERATOR
INCREMENT AND DECREMENT OPERATOR

COMPARISON OPERATOR

LOGICAL OPERATOR

EQUALITY OPERATOR
BITWISE OPERATOR

ESCAPE SEQUENCES

Subtopic 2: PHP Control Structures


PHP CONTROL STRUCTURES: CONDITIONAL STATEMENTS

if statement syntax: else statement syntax:


if(expression) { if(expression) {
statement… statement…
} } else {
statement
}

elseif statement syntax:


if(expression) {
statement…
}
elseif(expression) {
statement…
} else {
statement…
}
PHP CONTROL STRUCTURES: CONDITIONAL STATEMENTS (cont.)

Nested if…else

Compound Expression using logical operators

switch statement Syntax:


switch($category){
case opt1:
statement…
break;
case opt2:
statement…
break;
case opt3:
statement…
break;

default:
statement…
PHP CONTROL STRUCTURES: CONDITIONAL STATEMENTS (cont.)
Switch Statement

PHP CONTROL STRUCTURES: LOOPING STATEMENTS


while statement syntax:
while(expression){
statement…
}

do … while statement syntax:


do{
statement…
}while(expression);

for statement syntax:


for(expr1;expr2;expr3) {
statement…
}

EXAMPLE:
PHP CONTROL STRUCTURES: BREAK, CONTINUE, AND GOTO STATEMENT
Break
- break statement is placed within the code of a loop to cause the program to break out of the
loop statement.
Continue
- continue statement causes execution of the current loop iteration to end and commence at
the beginning of the next iteration.
goto … label:
- goto statement is used to jump to other section of the program to support labels.

EXAMPLE:

PHP CONTROL STRUCTURES: ALTERNATIVE ENCLOSURE SYNTAX


- Involves replacing the opening bracket with a colon(:) and replacing the closing bracket with
endif;, endwhile;,endfor;, endswitch
EXAMPLE:

SUMMARY:
- Simplifying expression needs to follow a general precedence set by PHP scripts.
- An operator specifies a particular action in a given expression.
- Available PHP operators are arithmetic, conditional, assignment, logical and bitwise operator.
- Operator precedence characteristics determines the order in which they evaluate the
operands surrounding them.
- Operator associativity characteristic specifies how operations of the same precedence are
evaluated as they are executed.
SUMMARY: (cont.)
- Post increment or decrement always execute the statement first before incrementing or
decrementing the value of a given variable.
- Pre increment or decrement always increment or decrement its variable value before
executing the statement.
- Escape sequence has its own special task in executing the string as an output.
- Conditional statements are statement the will execute statement inside a block if a given
condition is true
- Use compound expression to minimize the process of coding using nested if statement.
- break statement caused the program to break if used.
- continue statement end the current loop and continue to next iteration.
- goto statement used to jump to other section of the program.
- Alternative enclosure syntax is available for if, while, for, foreach, and switch control

Notes from Sir Renjun :>


OPERATORS – operators are used to perform operations on variables and values.
Types:
1. Arithmetic or Mathematical Operators
2. Assignment Operators
3. Increment and Decrement Operators
4. Comparison Operators
5. Logical Operators
6. String Operators

ARITHMETIC OR MATHEMATICAL OPERATORS


- it used with numeric values to perform common calculations or arithmetical operations.

ASSIGNMENT OPERATORS
- it is used with numeric values to write a value to variable.
- The basic assignment operators in PHP is "=". It means that the left operand get set to the value
of the assignment expression on the right.
PHP INCREMENT AND DECREMENT OPERATOR
- Increment operators are used to increment variables value.
- Decrement operators are used to decrement variables value.

PHP COMPARISON OPERATORS


- are used to compare two values (numbers or string).

- var_dump()functions is used to dump information about a variable

PHP LOGICAL OPERATORS


- are used to combine conditional statements.

PHP STRING OPERATORS

PHP CONTROL STRUCTURES / CONDITIONAL STATEMENTS


CONDITIONAL STATEMENTS – are used to perform different actions based on different conditions.
• if statement – executes some code if one condition is true.
• if else statement – executes some codes if a condition is true and another code if that
condition is false.
• if elseif else statement – executes different codes for more than two conditions
• switch statement – selects one of many blocks of code to be executed.

PHP IF STATEMENT
Syntax:
if(condition) {
code to be executed if condition is true;
}
PHP THE IF ELSE STATEMENT
- executes some codes if a condition is true and another code if that condition is false.
Syntax:
if(condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}

THE IF... ELSEIF.. ELSE STATEMENT


- executes different codes for more than two conditions
Syntax:
if(condition){
code to be executed if the condition is true;
}elseif (condition) {
code to be executed if first condition is false and this condition is true;
}else {
code to be executed if all conditions are false;
}

PHP SWITCH STATEMENT


- it is used to select one of many blocks of code to be executed.
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;
}

PHP LOOPS – are used to execute the same block of codes again and again as along as a certain
condition is true.
• while loop – loops through a block of codes as long as the specified condition is true.
• do while – loops through a block of codde once, and then repeats the loop as long as the
specified condition is true.
• for loops – loops through a block of code a specified numbers of times
• for each loops – loops through a block of code for each element in an array.
WHILE LOOP
Syntax:
while (condition is true){
code to be executed;
}

Explanation in Sample Program


$x = 1; - initialize that loop counter ($x) and set the start value 1.
$x<=5; - continue the loop as long as $x is less than or equal to 5.
$X++; - increase the loop counter value by 1 for each iteration

DO WHILE LOOP – It will always execute the block of code once, it will check t the condition, and
repeat the loop while the specified condition is true.
Syntax:
do {
code to be executed;
} while (condition is true);

FOR LOOP
Syntax:
for(int counter; test counter ; increment counter) {
code to be executed for each iteration;
}

Parameters:
• int counter – Initialize the loop counter value.
• test counter – Evaluate for each loop iteration. if it evaluates to True, the loop continues if it
evaluates to FALSE, the loop ends.
• increment counter – Increases the loop counter value.

Sample Program - Parameters


$x = 0 – initialize the loop counter ($x), and set the start value to 0.
$x<=10; – continue the loops as long as $x is less than or equal to 10
$X++; - increase the loop counter value by 1 for each iteration.

FOREACH LOOP
- for every loop iteration, the value of the current array element is assigned to $value and the
array pointer is moved by one, until it reaches the last array element.
Syntax:
foreach ($array as $value) {
code to be executed;
}
Subtopic 1: PHP Arrays and User Defined Functions
PHP ARRAYS
- ARRAYS – Is used to aggregate a series of similar items together, arranging and dereferencing them in
some specific way.
o Each member of the array index references a corresponding value and can be a simple
numerical reference to the value’s position in the series, or it could have some direct correlation
to the value.
o PHP array does not need to declare how many elements that the array variable have.
o Array index in PHP can be also called as array keys.
o Array can be used as ordinary array same as in C and C++ arrays

ARRAY: ONE DIMENSIONAL

Example: Code 1 Example: Code 2

Output:
Example: Code 3

ARRAY: FUNCTIONS FOR VISUALIZING ARRAYS


- print_r() function short for print recursive. This takes an argument of any type and prints it out, which
includes printing all its parts recursively.
- var_dump() function is same as the print_r function except that it prints additional information about the
size and type of the values it discovers print_r() and var_dump() functions are commonly used for
debugging. The point of this of these functions is to help you visualize what’s going on with compound
data structures like arrays.
- Example: using var_dump()
Example: using print_r()
Output
Output Example: using var_dump()
Example: using var_dump() :
:
ARRAY: LOOPING THROUGH ARRAY ELEMENTS
- foreach() function is a statement used to iterate or loop through the element in an array. With each
loop, a foreach statement moves to the next element in an array.
- foreach statement specify an array expression within a set of parenthesis following the foreach keyword.
o Syntax:

- $arr – The name of the array that you’re walking through.


- $key – The name of the variable where you want to store the key. (optional)
- $value – The name of the variable where you want to store the value
Example 1

Output
Example: using var_dump()
:

Example 2

Output
Example: using var_dump()
:
ARRAY: MULTIDIMENSIONAL ARRAYS

ARRAYS: SORTING

FUNCTIONS DESCRIPTION
sort($array) Sorts by value; assign new numbers as the keys
rsort($array) Sorts by value in reverse order; assign new number
asort($array) Sorts by value; keeps the same key
arsort($array) Sorts by value in reverse order; keeps the same key
ksort($array) Sorts by key
krsort($array) Sorts by key in reverse order
usort($array, functionname) Sorts by a function
ARRAYS: SORTING (cont.)

Subtopic 2: PHP Arrays and User Defined Functions


FUNCTIONS
- is a group of PHP statements that performs a specific task. Functions are designed to allow you to reuse
the same code in different locations.
o User defined functions – functions that are provided by the user of the program.
o Predefined functions – functions that are built-in into PHP to perform some standard operations
- Functions: User defined functions
o Syntax:
function name(param){
//code to be executed by the function
}
o function – is the keyword used to declare a function
o name – is the name of the function or function identifier
o param – is the formal parameters of the function. Parameter must follow the rule of naming
identifier.
FUNCTIONS (cont.)
- Functions: Function with no parameters

- Functions: Function that returns a value


- Functions: Nested function

- Functions: Variable scope


o Global Variables is one that declared outside a function and is available to all parts of the
program.
o Local Variables is declared inside a function and is only available within the function in which it is
declared.
o Static Variables is used to retain the values calls to the same function

- Functions: using variables


SUMMARY
- Array is used to aggregate a series of similar items together.
- Array index references a corresponding value.
- Array index can be simple numerical or have some direct correlation to the value.
- Array index is also known as Array Keys.
- print_r function is used to print the array structure.
- var_dump function is same as print_r function except it adds additional information about the data of
each element.
- The foreach statement is use to iterate through the element in an array.
- Using foreach statement you can display both the keys and value of each element in the array.
- PHP provides functions for array manipulation such as sort(), rsort(), asort(), arsort(), ksort(), krsort(), and
usort() functions.

Subtopic 1: Constants, Files and Mathematical Functions


USING CONSTANT
- define() functions – used to declare constants. A constant can only be assigned a scalar value, like a
string or a number. A constant’s value cannot be changed.
- Syntax: define(‘NAME’,’value’);

INCLUDING FILES
- You can separate your PHP file and embed it to your html by using PHP include functions.

INCLUDE FUNCTIONS DESCRIPTION


include Includes and evaluates the specified file. Generate a warning on failure message if
file not found.
require Performs the same way as the include function. Generate a fatal error message if
file not found stopping the script at that point
include_once Same as include function except it includes the file only once.
require_once Same as require function except it includes the file only once

- Most of the developers used include functions for their header and footer. Also, some use this to write
their database connection and so on.
- You may write the file with an extension name of .inc rather than .php to serve as a fragment of your
program code.
- In some scripts, a file might be included more than once, causing function redefinitions, variable
reassignments, and other possible problems.
- Syntax:
o include(“filename.inc”);
o include_once(“filename.inc”);
o require(“filename.inc”);
o require_once(“filename.inc”);
INCLUDING FILES (cont.)
- Including Files: include() function (file not found)

- including Files: require() function (file not found)

- Including Files: include()function (file exists)


header.inc

Same output using require function

MATHEMATICAL FUNCTION
- rand() function – used to generate random integers
o syntax:
▪ int rand(void)
▪ int rand(int $min, int $max)
- ceil() function – returns the next highest integer by rounding the value upwards
o syntax: float ceil(float $value)
- floor() function – returns the next lowest integer by rounding the value downwards
o syntax: float floor(float $value)
- min() function – Return the smallest value
o syntax:
▪ mixed min(array $values)
▪ mixed min(mixed $values1, mixed $values2[,mixed $...])
- max() function – Return the highest value
o syntax
▪ mixed max(array $values)
▪ mixed max(mixed $values1, mixed $values2[,mixed $...])
MATHEMATICAL FUNCTION (cont.)
- Mathematical Function: rand(), ceil(), floor(), min(), max()

- Mathematical Function: number_format() function


o Format a number with grouped thousand
o Syntax

Subtopic 2: Array, String and Date Manipulation


FUNCTION FOR ARRAY MANIPULATION
- unset function - destroys the specified variable
o syntax: void unset ( mixed $var [, mixed $... ] )
- explode function
o split a string by string
o syntax:
array explode ( string $delimiter ,
string $string [, int $limit ] )
- implode function
o join array elements to form a string
o syntax:
▪ string implode ( string $glue , array $pieces )
▪ string implode ( array $pieces )
FUNCTION FOR ARRAY MANIPULATION (cont.)
- Function for Array Manipulation: unset(), explode(), implode()

FUNCTION FOR STRING MANIPULATION


- strlen function
o return the value length of a string
o syntax: int strlen (string $string)
- strpos function
o find the position of the first occurrence of a substring in a given string
o syntax:
int strpos ( string $haystack ,
mixed $needle [, int $offset = 0 ] )
- strrev function
o reverse a given string
o syntax: string strrev ( string $string )
- strtolower function
o converts string to lowercase
o syntax: string strtolower ( string $str )
- strtoupper function
o converts string to uppercase
o syntax: string strtoupper ( string $str )
- substr function
o returns part of a given string
o syntax:
string substr ( string $string ,
int $start [, int $length ] )

- Function for String Manipulation: strlen(), strpos(), strrev(), strtolower(), strtoupper(), substr()
FUNCTION FOR STRING MANIPULATION (cont.)
- ucfirst() function
o Make a string’s first character uppercase
o syntax: string ucfirst( string $str )
- ucwords() function
o converts string to uppercase
o syntax: string ucwords ( string $str )
- trim() function
o stripped white spaces or other characters from the beginning and end of a string.
o syntax: string trim ( string $str [, string $charlist ]
- ltrim() function
o strip white spaces or other characters from the beginning of a string.
o syntax: string ltrim ( string $str [, string $charlist ] )
- rtrim() function
o strip white spaces or other characters from the end of a string.
o syntax: string rtrim ( string $str [, string $charlist ] )
- strip_tags() function
o strip HTML and PHP tags from a string.
o syntax: string strip_tags ( string $str [, string $allowable_tags ] )

- Function for String Manipulation: ucfirst(), ucwords(), trim(), ltrim(), rtrim(), strip_tags()
DATE MANIPULATION: DATE() FUNCTION
- used to format a local time or date
- returns a string formatted according to the given format string.
- syntax: string date ( string $format [, int $timestamp = time() ] )
DATE MANIPULATION: DATE() FUNCTION (cont.)

- Date Manipulation: date() Function


- Date Manipulation: mktime() function
o get the unix timestamp (January 1, 1970) for a given date. (with strict notice)
o same as time() function (without strict notice)
o syntax:
▪ int mktime ([ int $hour = date("H")
[, int $minute = date("i")
[, int $second = date("s")
[, int $month = date("n")
[, int $day = date("j")
[, int $year = date("Y")
[, int $is_dst = -1 ]]]]]]] )

- Date Manipulation: strtotime() function


o parse any English textual datetime description into a Unix timestamp
o syntax:
int strtotime ( string $time
[, int $now = time() ] )

NOTES FROM SIR:


PHP Arrays
- an array stores multiple values in one single variable.
- is special variable which can hold more than one value at a time.
- Syntax: array();

PHP Array: three types


1. Indexed Array array with numeric index.
2. Associative Array – arrays with named keys.
3. Multidimensional Array – arrays containing one or more arrays

count () function – Is used to return the length (the number of elements)of an array.

Indexed Array – the numeric indexed always starts at 0.

Syntax: $fruits[0] = "Banana";


$fruits[1] = "Apple";
$fruits[2] = "Guyabano";

Associative Array – are arrays that use named keys that you assign to them.
Ex: $age ['Peter'] = "35";
$age ['Jeffrey'] = 37";
$age ['Buban'] = "43";

• foreach() function - statement used to iterate or loop through the element in an array.
• $key - the name of the variable where you want yo store the key(optional)
• $value - the name of the variable where you want to store the value.

PHP Multidimensional Arrays – an array containing one or more arrays.


- The dimension of an array indicates the number of indices you need to select an element.
- For two dimensional array you need two indices to select an element
- For a three dimensional array you need three indices to select an element.
Example:
Name Stock Sold
Mango 22 18
Apple 15 13
Banana 5 2
Guyabano 17 15

$fruits = array (
array("Mango" , 22, 18),
array("Apple" , 15, 13),
array("Banana" , 5, 2),
array("Guyabano" , 17, 15));

$fruits array contains four array and it has two indices: row and column
PHP Sorting Arrays – the elements in an arrray can be sorted in apphabetical or numerical order, descending or
ascending.
sort() function - sort arrays in ascending order.
rsort() function - sort arrays in descending order.
asort() function - sort associative arrays in ascending order accdg. to the value.
ksort() function - sort associative arrays in ascending order accdg the key.
arsort() function - sort associative arrays in descending order to the value
krsort() function - sort associative arrays in descending order accdg to the key.

PHP Functions
- is a group of statements that performs a specific task. Functions are design to allow you to reuse the same
code in different locations.

2 TYPES OF FUNCTIONS:
1. User defined functions – functions that are provided by the user of the program.
2. Predefined Functions – functions that are built in into PHP to perform some standard operations.

PHP User Defined Functions


- a function is a block of statement that can be used repeatedly in a program.
- a function will not execute automatically when a page loads
- a function will be executed by a call to the function.

Syntax: function functionName(parameter) { • function – is the keyword used to declare a


code to be executed function
} • functionName – Is the name of the function
or function identifier
• parameter – argument

Sample Program:
<html>
<body> Explanation:
- We created function named writeMsg()
<?php - the opening curly brace indicated the
function writeMsg(){ beginning of the function code and the
echo "Hello Philippines!!!"; closing curly brace indicates the end of the
}
function
writeMsg(); // call of the function
- The function outputs the "Hello Philippines!!!"
?>
</body> - To call the function, just write its name
<html> followed by parenthesis ();
CCS0043LL

PHP Function Arguments


- Information can be passed to functions through arguments. An argument is just like a variable.
- Arguments are specified after the functionname inside the parantheses. You can add as many
arguments as you want, just separate them with a comma.

<html>
<body>
<?php
function familyName($fname){
echo "$fname Buban. <br>";
}
familyName("Michael");
familyName("Allah");
familyName("Jeffrey");
?>
</html>
</body>

strict function – it will throw a Fatal Error if the data type mismatched.
Syntax: (strict_types = 1);

Sample Program:
<html>
<body>
<?php declare (strict_type = 1);
function AddNumber (int $a, int $b) {
return $a + $b;
}
echo AddNumber(5,"5 days");
?>
</body>
</html>

PHP Functon returning Values – to let a function return a value, use the return statement

<html>
<body>
<?php
function sum(int $x, int $y){
$z = $x+$y;
return $z;
}
echo "5+10 =" . sum(5,10) . "<br>";
echo "10+3 =" . sum(10,3) . "<br>";
echo "4+8 =" . sum(4,8);
?>
</body>
</html>
Passing Arguments by References
- In Php, arguments are usually passed by value, which means that a copy of the value is used in the
function and the variable that was passed into function connot be changed.

- When a function argument is passed by reference, changes to the argument also change the variable
that was passed in. To turn a function argument into reference the & operator is used.

Sample Program:
<html>
<body>
<?php
function add_five(&$value){
$value += 5;
}
$num = 2;
add_five($num);
echo $num;
?>
</html>
</body>

Subtopic 1: Global Variables


SUPERGLOBAL VARIABLES
- $_SERVER
o is an array containing information such as headers, paths, and script locations.
o entries were created by the web server
o Index ‘PHP_SELF’ contains the filename of the currently executing script.
- $_GET
o an associative array variables passed to the current script via the URL parameters.
- $_POST
o an associative array of variables passed to the current script via the HTTP POST method.
- $_REQUEST
o an associative array that by default contains the contents of $_GET, $_POST, and $_COOKIE
- $_COOKIE
o an associative array of variables passed to the current script via HTTP Cookies
- $_SESSION
o an associative array containing session variables available to the script
- $_ENV
o an associative array of variables passed to the current script via the environment method
SUPERGLOBAL VARIABLES
EXAMPLE

OUTPUTS

before button was clicked submit get button was clicked submit post button was clicked

COOKIES
- are mechanism for storing data in the remote browser and thus tracking or identifying return users.
- small amount of information containing variable=value pair (user’s computer).
- users can refuse to accepts cookies.
- Managing cookies can be done using setcookie() function
- syntax: setcookie()
bool setcookie ( string $name [, string $value [, int
$expire = 0 [, string $path [, string $domain [, bool
$secure = false [, bool $httponly = false ]]]]]] )
Example: PHPSetCookies.php Output 1: cookies were set
COOKIES (cont.)

Example: PHPDisplayCookies.php Output 2: after 10 secs

Example: PHPDeleteCookies.php
Output 3: delete cookies

Subtopic 2: Session
SESSION
- are mechanism for storing data on the server itself.
- is the time that a user spends at your Web site.
- more secure than cookies and can store much more information
- to open a session use session_start() function
o always set at the beginning of each Web page.
- to close the session use session_destroy() function
o gets rid of all the session variable information that’s stored in the session file.
o the statement does not affect the variables set on the current page
- to unset session variables use unset() function
o syntax: unset($_SESSION[ ‘Varna me’]);

Example: PHPUnsetSession.php
Example: PHPSetSession.php

Example: PHPDeleteSession.php

Example: PHPDisplaySession.php
REGULAR EXPRESSION
- were used to efficiently search for patterns in a given text.
- also known as regex or regexp.
- PHP implements Percl Compatible Regular Expression (PCRE)
- PCRE function starts with preg_
- preg_match() function
o Performs a regular expression match
o Syntax: int preg_match ( string $pattern , string $subject [, array &$matches
[, int $flags = 0 [, int $offset = 0 ]]] )

REGEX META CHARACTERS

REGEX PATTERN MODIFIERS


REGULAR EXPRESSION (cont.)
EXAMPLE

USEFUL REGEX FUNCTIONS


EMAIL VALIDATION
Subtopic 1: Database
INTRODUCTION TO DATABASES
- Database – is an ordered collection of information from which a computer program can quickly access.
- Information stored in computer databases is actually stored in tables similar to spreadsheet.
- A record in a database is a single complete set of related information.
- Fields are the individual categories of information stored in a record.
Example: Employee Directory DB

Also called as flat-file database that stores information in a single table

RELATIONAL DATABASE
- Stores information across multiple related tables.
- Composed of Primary Table and Related Table (child table)
• Primary key is a field that contains a unique identifier for each record in a primary table.
• Foreign key is a field in a related table that refers to the primary key in a primary table.
• Normalization is the process of breaking tables into multiple related tables to reduce redundant
information.

THE MySQL DATABASE


- One important aspect of database management is its querying capability.
- A query is a structured set of instructions and criteria for retrieving, adding, modifying, and deleting
database information.
- Data Manipulation Language (DML) is use for creating queries.
- Structured Query Language (SQL) has a standard data manipulation language among many database
management system

OPEN SOURCE DATABASE


- Either as outgrowths of earlier
- academic research (PostgreSQL)
- Developments of lightweight storage tools for websites (MySQL)
- Open-sourced commercial products (InterBase)
o Most popular open source relational database
o An Australian academician named David Hughes (Hughes Technologies) wrote a very
lightweight database engine called mSQL (short for mini SQL) -- it didn't implement a number of
features required for full ANSI SQL certification, but it was very small and very fast.
o mSQL was distributed as shareware • incapable of doing a number of essential things -- like joins

A BIT HISTORY
- improvement was done by a Swedish programmer Monty Widenius
- MySQL rapidly grew until, although it's still a fast, light database, it's also a pretty powerful one.
- MySQL is written in C++, compiles using GNU gcc, and is pretty portable -- it has been ported to OS/2,
Windows 95 and NT, as well as a variety of flavours of UNIX
FEATURES OF SQL
- According to the article of Ian Gilfillan in 2004, the following are the claimed features of MySQL:
• High availability
• High scalability
• High performance

CONNECTING TO MySQL: Console Base


- Console Base
- Go to the Command Window
Start\Run
Type command or cmd
- Go to the MySQL path
C:\xampp\mysql\bin\mysql –u root –p
C:\xampp\mysql\bin\mysql –u root
- **Enter password if there is any.
Type commands in MySQL prompt which looks like this:
MySQL Log in

MySQL Prompts

Example:
BASIC COMMANDS
- To clear command:
o mysql > \c
- Get status from the server:
o mysql > status
o mysql > \s
- Need help?:
o mysql > \h
o mysql > ?
o mysql > \?
o mysql > help
- To display the SQL version:
o mysql > select version();

EXAMPLE:

- Display current user:


o mysql > select user();
- Display current date:
o mysql > select current_date();
- Display today’s date and time:
o mysql > select now()

- To quit
o mysql > \q
o mysql > quit
o mysql > exit
Subtopic 2: MySQL
- Data manipulation Language (DML)
- Create, Select, Insert, Update, Delete

DATABASE CREATION
- SYNTAX: CREATE DATABASE <databasename>;
o mysql> CREATE DATABASE DBStudent;
- Showing and Using the Database:
o mysql> SHOW databases;
- SYNTAX: USE <database name>;
o mysql> USE DBStudent;
Note: It should display Query OK, 1 row affected as a result.

TABLE CREATION
- SYNTAX: CREATE TABLE <table name> (field name field type(size) condition...);
o mysql> CREATE TABLE tblStudent(id int(5) primary key not null auto_increment, name char(25));
- Display the structure of the table:
o SYNTAX: DESCRIBE <table name>;
- mysql > DESCRIBE tblStudent;
- Displaying the list of table: mysql> SHOW tables;

SAMPLE SCREEN

ADDING OF PRIMARY KEY


• mysql> create table primaryTable (id int not null auto_increment, name varchar(30), primary key (id));
• mysql> create table keyTable (id int not null auto_increment, name varchar(30), key (id));
• mysql> create table uniqueTable (id int not null auto_increment, name varchar(30), unique key (id));

FIELD DATA TYPES


The ‘show’ Command
- This time you can show additional information of a table
o mysql > SHOW COLUMNS FROM tblStudent;
o mysql > SHOW TABLE STATUS;
o mysql > SHOW TABLE STATUS \G;
o mysql > SHOW TABLE STATUS LIKE ‘tblStudent’ \G;
o mysql > SHOW CREATE TABLE tblStudent \G;
EXAMPLE:

MODIFYING THE TABLE STRUCTURE


- Adding new column
- Syntax: ALTER TABLE <table name> ADD <column name> <data type(size)>;
MODIFYING THE TABLE STRUCTURE
- Changing Field Type Sizes
o Syntax: ALTER TABLE <table name> MODIFY <column name> <data type(size)>;
o mysql > ALTER TABLE tblStudent MODIFY gender char(7);

- Changing Field Names


o Syntax: ALTER TABLE <table name> CHANGE <column name> <new column name> <data
type(size)>;
o mysql > ALTER TABLE tblStudent CHANGE gender sex char(7);

- Dropping column
o Syntax: ALTER TABLE <table name> DROP <column name>;

INSERTING VALUES TO YOUR TABLE


- Syntax: INSERT INTO <table name> VALUES (value1, value2, value3, ....);
- mysql > INSERT INTO tblStudent VALUES (10001, ‘Juan Dela Cruz’);
- To view use ‘SELECT’ command:
- Syntax: SELECT * FROM <table name>;
- mysql> SELECT * FROM tblStudent;
INSERTING VALUES IN A SPECIFIC COLUMN
- Syntax: INSERT INTO <table name> (column name) VALUES (value);

OTHER STRUCTURE

UPDATING THE RECORDS


- Syntax: UPDATE <table name> SET <column name> = <value> WHERE <column name> = <value>;

UPDATING MULTIPLE COLUMNS


- Syntax: UPDATE <table name> SET <column name> = <value>, <column name> = <value> WHERE
<column name> = <value>;
DELETING OF COLUMNS
- Syntax: DELETE FROM <table name> WHERE <column name> = <value>;

DELETING ALL DATA IN A TABLE


- Syntax: TRUNCATE TABLE <table name> or
o mysql> TRUNCATE TABLE tblStudent;
o mysql> DELETE FROM tblStudent;

TO DELETE A TABLE
- Syntax: DROP TABLE <table name>;
o mysql> DROP TABLE tblStudent;
- * You remove a table from the database when it is not required. You use the DROP TABLE statement to remove
a table. When you remove a table, all the data from the table is also deleted.

TO DELETE DATABASE
- Syntax: DROP DATABASE <database name>;
- mysql> DROP DATABASE dbStudent;

Subtopic 1: Files Functions


USING GROUP FUNCTIONS
- Example: SUM
mysql_result()
- mysql_result() retrieves the contents of one cell from a MySQL result set
- Syntax:
mysql_result($result_query, row, field)
$result_query
- The result resource that is being evaluated. This result comes from a call to mysql_query().
- row - The row number from the result that's being retrieved. Row numbers start at 0.
- field - The name or offset of the field being retrieved
- Example: mysql_result()

- Example: MAX

- Example: MIN
mysql_affected_rows()
- mysql_affected_rows() get the number of affected rows by the last SELECT, INSERT, UPDATE, REPLACE or
DELETE query.
- Syntax: mysql_affected_rows()
- Example:

- mysql_num_rows() retrieves the number of rows from a result set. This command is only valid for
statements like SELECT or SHOW that return an actual result set.
- Syntax: mysql_num_rows()
- Example:

More MySQL Functions Visit


- http://www.php.net/manual/en/ref.mysql.php
- http://w3schools.com/php/php_ref_mysql.asp
WORKING WITH FILE UPLOADS
$_FILES
- Using the global PHP $_FILES array you can upload files from a client computer to the remote server.
- Syntax: $_FILES[“file”][“index”]
o file – the name of the field in the form
o index – specifies the parameter to be processed by $_FILES

CREATE THE UPLOAD FORM


SAVING FILE PERMANENTLY
- To save permanently the uploaded file, use the move_uploaded_file() function. This function returns
- TRUE on success, or FALSE on failure.
- Syntax: move_upload_file(file, new location);
- Example:

EXAMPLE

Subtopic 2: PHP Validations


VALIDATING FILES
EXAMPLE

CREATING AND DELETING FILES


- touch() - attempts to create an empty file. If the file already exists, its contents won't be disturbed, but
the modification date will be updated to reflect the time at which the function executed.
o Example: touch(“myfile.txt”);
- unlink() – a function used to remove an existing file.
o Example: unlink(“myfile.txt”);

OPENING A FILE FOR WRITING, READING, OR APPENDING


- fopen() – is used to open a file for reading, writing or appending content
- Syntax: fopen(“file”, “mode”);
- Example:
o fopen(“test.txt”, “r”) – for reading
o fopen(“test.txt”, “w”) – for writing
o fopen(“test.txt”, “a”) – for appending
o fclose() – to close a file
READING LINES FROM A FILE
- fgets() – to read a line from a file
- feof() – to tell the last line of a file

- fread() – to read a specified set of character in a file


- fgetc() – to read a file per character

WRITING AND APPENDING TO A FILE


- The fwrite() function accepts a file resource and a string, and then writes the string to the file
- The fputs() function works in exactly the same way.

You might also like