2. Agenda
Core PHP
· Software Engineering
· Web Programming
· Introduction to PHP
· HTML and CSS
· PHP as a Scripting Language
· Variables and Expressions in PHP
· PHP Operators
· Conditional Test, Events and Flows in PHP
· Functions and Arrays using PHP
· PHP Syntax and Variables
· String functions
· DBMS&RDBS
· MYSQL database and queries
· Sessions and Cookies in PHP
· Files and Directory Access
· Handling e-mail
· Use of JavaScript, AJAX and XML
3. Program..
Sequence of instructions written for specific purpose
Like program to find out factorial of number
Can be written in higher level programming languages
that human can understand
Those programs are translated to computer
understandable languages
Task will be done by special tool called compiler
4. Compiler will convert higher level language code to
lower language code like binary code
Most prior programming language was ‘C’
Rules & format that should be followed while writing
program are called syntax
Consider program to print “Hello!” on screen
5. void main()
{
printf(“Hello!”);
}
Void main(), function and entry point of compilation
Part within two curly brackets, is body of function
Printf(), function to print sequence of characters on
screen
6. Any programming language having three part
Data types
2. Keywords
3. Operators
Data types are like int, float, double
Keyword are like printf, main, if, else
The words that are pre-defined for compiler are
keyword
Keywords can not be used to define variable
1.
7. We can define variable of data type
Like int a; then ‘a’ will hold value of type int and is
called variable
Programs can have different type of statements like
conditional statements and looping statements
Conditional statements are for checking some
condition
8. Conditional Statements…
Conditional statements controls the sequence of
statements, depending on the condition
Relational operators allow comparing two values.
1. == is equal to
2. != not equal to
3. < less than
4. > greater than
5. <= less than or equal to
6. >= greater than or equal to
9. SIMPLE IF STATEMENT
It execute if condition is TRUE
Syntax:
if(condition)
{
Statement1;
.....
Statement n;
}
10. main()
{
int a,b;
printf(“Enter a,b values:”);
scanf(“%d %d”,&a,&b);
if(a>b) {
printf(“n a is greater than b”); }
}
OUTPUT:
Enter a,b values:20 10
a is greater than b
11. IF-ELSE STATEMENT
It execute IF condition is TRUE.IF condition is FLASE it execute ELSE
part
Syntax:
if(condition)
{
Statement1;
.....
Statement n;
}
else
{
Statement1;
.....
Statement n;
}
12. main()
{
int a,b;
printf(“Enter a,b values:”);
scanf(“%d %d”,&a,&b);
if(a>b) {
printf(“n a is greater than b”); }
else {
printf(“nb is greater than b”); }
}
OUTPUT:
Enter a,b values:10 20
b is greater than a
13. IF-ELSE IF STATEMENT:
It execute IF condition is TRUE.IF condition is FLASE it checks ELSE IF
part .ELSE IF is true then execute ELSE IF PART. This is also false it
goes to ELSE part.
Syntax:
if(condition)
{
Statementn;
}
else if
{
Statementn;
}
else
{
Statement n;
}
14. main()
{
int a,b;
printf(“Enter a,b values:”);
scanf(“%d %d”,&a,&b);
if(a>b) {
printf(“n a is greater than b”); }
else if(b>a) {
printf(“nb is greater than b”); }
else {
printf(“n a is equal to b”); }
}
OUTPUT:
Enter a,b values:10 10
a is equal to b
15. NESTED IF STATEMENT
To check one conditoin within another.
Take care of brace brackets within the conditions.
Synatax:
if(condition)
{
if(condition)
{
Statement n;
}
}
else
{
Statement n;
}
16. main()
{
}
int a,b;
printf(“n Enter a and b values:”);
scanf(“%d %d ”,&a,&b);
if(a>b) {
if((a!=0) && (b!=0)) {
printf(“na and b both are +ve and a >b);
else {
printf(“n a is greater than b only”) ; } }
else {
printf(“ na is less than b”); }
}
Output:
Enter a and b values:30 20
a and b both are +ve and a > b
17. Switch..case
The switch statement is much like a nested if .. else statement.
switch statement can be slightly more efficient and easier to
read.
Syntax :
switch( expression )
{
case constant-expression1:
statements1;
case constant-expression2:
statements2;
default :
statements4;
}
18. main()
{
char Grade = ‘B’;
switch( Grade )
{
case 'A' :
printf( "Excellentn" ); break;
case 'B' :
printf( "Goodn" ); break;
case 'C' :
printf( "OKn" ); break;
case 'D' :
printf( "Mmmmm....n" ); break;
default :
printf( "What is your grade anyway?" );
break;
}
}
19. Looping…
Loops provide a way to repeat commands and control how
many times they are repeated.
C provides a number of looping way.
while loop
A while statement is like a repeating if statement.
Like an If statement, if the test condition is true: the
statements get executed.
The difference is that after the statements have been
executed, the test condition is checked again.
If it is still true the statements get executed again.
This cycle repeats until the test condition evaluates to false.
20. Basic syntax of while loop is as follows:
while ( expression )
{
Single statement or Block of statements;
}
Will check for expression, until its true when it gets
false execution will be stop
21. main()
{
int i = 5;
while ( i > 0 ) {
printf("Hello %dn", i );
i = i -1; }
}
Output
Hello 5
Hello 4
Hello 3
Hello 2
Hello 1
22. Do..While
do ... while is just like a while loop except that the test
condition is checked at the end of the loop rather than
the start.
This has the effect that the content of the loop are
always executed at least once.
Basic syntax of do...while loop is as follows:
do {
Single statement or Block of statements;
}
while(expression);
Version 1.4
23. main()
{
int i = 5;
do{
printf("Hello %dn", i );
i = i -1; }
while ( i > 0 );
}
Output
Hello 5
Hello 4
Hello 3
Hello 2
Hello 1
24. For Loop…
for loop is similar to while, it's just written differently.
for statements are often used to proccess lists such a
range of numbers:
Basic syntax of for loop is as follows:
for( initialization; condition; increment)
{ Single statement or Block of statements;
}
25. main()
{
int i; int j = 5;
for( i = 0; i <= j; i ++ )
{
printf("Hello %dn", i );
}
}
Output
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
26. Break & Continue…
C provides two commands to control how we loop:
break -- exit form loop or switch.
continue -- skip 1 iteration of loop.
Break is used with switch case
27. main()
{
int i; int j = 5;
for( i = 0; i <= j; i ++ ) {
if( i == 3 )
{
break;
}
printf("Hello %dn", i ); }
}
Output
Hello 0
Hello 1
Hello 2
Version 1.4
28. Continue Example..
main()
{
int i; int j = 5;
for( i = 0; i <= j; i ++ )
{
if( i == 3 )
{
continue;
}
printf("Hello %dn", i );
}
}
Output
Hello 0
Hello 1
Hello 2
Hello 4
Hello 5
Version 1.4
29. Functions…
A function is a module or block of program code which
deals with a particular task.
Making functions is a way of isolating one block of
code from other independent blocks of code.
Functions serve two purposes.
1.
2.
They allow a programmer to say: `this piece of code
does a specific job which stands by itself and should
not be mixed up with anything else',
Second they make a block of code reusable since a
function can be reused in many different contexts
without repeating parts of the program text.
Version 1.4
30. int add( int p1, int p2 ); //function declaration
void main()
{
int a = 10;
int b = 20, c;
c = add(a,b); //call to function
printf(“Addition is : %d”, c);
}
int add( int p1, int p2 ) //function definition
{
return (p1+p2);
}
Version 1.4
31. Exercise…
1.
2.
3.
4.
5.
Find out factorial of given number
Check whether given number is prime number or
not
Check whether given number is Armstrong number
or not
Calculate some of first 100 even numbers
Prepare calculator using switch
Version 1.4
32. OOPS Fundamentals…
Class – group of data members & member functions
Like person can be class having data members height
and weight and member functions as get_details() and
put_details() to manipulate on details
Class is nothing until you create it’s object
Object – instantiates class allocates memory
Version 1.4
33. OOPS Fundamentals…
Access to data members & member functions can be
done using object only (if they are not static!)
OOPS features are
1.
2.
3.
4.
5.
Encapsulation
Data hiding
Data reusability
Overloading (polymorphism)
Overriding
Version 1.4
34. OOPS Features…
Encapsulation – making one group of data members &
member functions
Can be done through class
Then group of data members & Member functions will
be available just by creating object.
Version 1.4
35. OOPS Features…
Data Hiding – can be done through access modifiers
Access modifiers are private, public, protected and
internal
Private members or member function won’t be
available outside class
Public – available all over in program outside class also
Version 1.4
36. OOPS Features…
Protected – members that are available in class as well
as in it’s child class
Private for another class
Protected access modifier comes only when
inheritance is in picture
Internal is used with assembly creation
Version 1.4
38. OOPS Features…
Overloading – taking different output of one method
or operator based on parameters and return types
Like add() method performs addition and add(int a,int
b) performs addition of ‘a’ and ‘b’ passed when calling
Also, + operator performs addition of two numbers as
well as concatenation of strings
Version 1.4
39. class arith
{
public:
void calc(int num1)
{
cout<<"Square of a given number: " <<num1*num1 <<endl;
}
};
void calc(int num1, int num2 )
{
cout<<"Product of two whole numbers: " <<num1*num2 <<endl;
}
int main() //begin of main function
{
arith a;
a.calc(5);
a.calc(6,7);
}
This is example of method overloading, output will be
Square of given number : 25
Product of two whole numbers : 42
Version 1.4
40. OOPS Features…
Data Reusability – helps in saving developers time
You can use already created class to crate new one
Called inheritance
Already existing class is base class and new created is
derived class
Base class members can be available in derived class
and to access them create object of derived class
Like from parent to child
Version 1.4
41. class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b;}
};
class CRectangle: public CPolygon {
public: int area ()
{ return (width * height); }
};
class CTriangle: public CPolygon {
public: int area ()
{ return (width * height / 2); } };
int main () {
CRectangle rect;
CTriangle trgl; rect.set_values (4,5);
trgl.set_values (4,5);
cout << rect.area() << endl;
cout << trgl.area() << endl;
return 0;
}
Version 1.4
42. OOPS Features…
In C++, overriding is a concept used in inheritance which involves a
base class implementation of a method.
Then in a subclass, you would make another implementation of the
method. This is overriding. Here is a simple example.
class Base
{
public:
virtual void DoSomething() {x = x + 5;}
private:
int x;
};
class Derived : public Base
{
public:
virtual void DoSomething() { y = y + 5; Base::DoSomething(); }
private:
int y;
};
Version 1.4
43. What is Website?
Website – Everyday you visit on internet
Follows some rules & regulations i.e. client-server
architecture standard
Websites – providing information from anywhere in
world
Version 1.4
45. Client-Server…
Client – end user’s computer that runs software or
website
Server – area in host or remote computer to which
client communicates
Network – means of communication
Can be HTTP(for www), FTP(machine to machine
transfer),SMTP(mail transfer)
Version 1.4
46. Website – basic parts
Websites are consist of three parts
GUI – web pages that you visit
Coding – logic that provides functionality or makes
website dynamic
Database – manages data provided by end user
For GUI building HTML is used from long time
Version 1.4
47. HTML…
HTML is the "mother tongue" of your browser.
HTML – Hypertext Markup Language
HTML is a language, which makes it possible to
present information on the Internet.
What you see when you view a page on the
Internet is your browser's interpretation of HTML.
To see the HTML code of a page on the Internet,
simply click "View" in the top menu of your
browser and choose "Source".
Version 1.4
48. HTML…
HTML documents are defined by HTML elements.
An HTML element starts with a start tag / opening
tag
An HTML element ends with an end tag / closing tag
The element content is everything between the start
and the end tag
Some HTML elements have empty content
Empty elements are closed in the start tag
Most HTML elements can have attributes
Ex : <p>This is paragraph</p>
Version 1.4
49. HTML…
Attributes provide additional information about
HTML elements.
Attributes provide additional information about an
element
Attributes are always specified in the start tag
Attributes come in name/value pairs like:
name="value“
For ex: <p id=“p1”>This is paragraph</p>
Version 1.4
51. Explanation…
Content between <html> and </html> is considered as
html content
Content between <head> and </head> will be
considered as head part
<title> and </title> is title of page that will be shown
in browser
<body> and </body> is part of page that will be filled
with controls
Version 1.4
52. Database…
Back end part of website
Used to maintain information provided by users
Built up with list of tables, tables having rows and
columns
Data in cells are records
When tables are connected in database system it is
RDBMS.
Version 1.4
53. Database…
A DBMS that follows rules of Dr.E.F.Codd is RDBMS
RDBMS stores data in form of tables and relation ship
between those tables in form of tables
Ideally there is no DBMS exist that follows all rules of
E.F.Codd!
Version 1.4
55. Database…
Queries – sentences executed on database for data
manipulation
Will be handled by database engines and will perform
action on data that are stored on database server
Ex are create, alter, insert, update, delete etc
SQL – structured query language is used for this
Version 1.4
56. SQL
DDL – data definition Language
Commands are : create, alter, truncate, drop
Syntax :
create table table_name(col_name datatype(size)…);
Example :
Create table Person_Master(name nvarchar(50));
Version 1.4
57. SQL
DML – data manipulation language
Like insert, update, delete
Syntax:
insert into table_name(col1,col2,..coln)
values(val1,val2,..valn);
Example:
insert into Person_Master(name) values(‘name1’);
Version 1.4
58. SQL
Update Syntax:
update table_name set col1=val1, col2=val2 where col =
val;
Ex :
update Person_Master set name = ‘name1’ where ID=1;
It will set name to ‘name1’ for which ID is 1
Version 1.4
59. SQL
Delete syntax :
delete from table_name where condition;
Example :
delete from Person_Master where ID=1;
It will delete whole row for which ID is 1
It is conditional delete operation
To delete all rows simply omit the condition
Version 1.4
60. SQL
Select syntax :
select * from table_name;
It will select all rows from specified table
To select particular row
select * from table_name where condition;
To select particular column
select col1,col2 from table_name;
Version 1.4
61. Database…
Constrains – terms that needs to be satisfied on data
For ex all students must have unique roll number
Can be defined as primary key, foreign key, unique key
etc.
Primary key – column of table whose value can be used
to uniquely identify records
Version 1.4
62. Database…
Foreign key – column inside table that is primary key
of another table
Unique key – like primary key can be used to uniquely
identify a record
Difference between primary key and unique key is
primary key will never allow null where as unique key
will allow it for once
Version 1.4
63. Normalization…
The process of structuring data to minimize
duplication and inconsistencies.
The process usually involves breaking down the single
table into two or more tables and defining
relationships between those tables.
Normalization is usually done in stages.
Most people in creating database, never need to go to
beyond the third level of normalization.
Version 1.4
64. 1NF
Eliminate duplicative columns from the same table.
Create separate tables for each group related data and
identify each row with a unique columns.
In this, one table will be divided in two tables with
relevant contents
Version 1.4
65. 2NF
Once 1NF has been done then and only then 2NF can
be done
In this, provide key constrains to the columns of tables
based on uniqueness
Like assign primary key to one table column and refer
this as foreign key in another table
Version 1.4
66. 3NF
Only after 2NF, third normalization can be done
In this, further more analyze tables and divide them
for data uniqueness
Version 1.4
67. SDLC…
For project development rules & regulation need to be
followed for best quality output at defined time limit
Rules are Software Development Life Cycle – SDLC
It’s part of software engineering
Six rules to be followed…
Version 1.4
69. SDLC…
1. Requirement collection
Phase of collecting requirements from client
Will be done by business analyst of company
He will create questioner, in which put answers from client
2. Analysis & SRS (Software Requirement Specification)
Collected requirements will be analyzed for time limit,
budget and market trade
Will be filtered and SRS will be created as result
Will be discussed with client
Version 1.4
70. SDLC…
1.
Based on requirements users, their activities and flow of data,
modules will be defined
Will be done by system analyst
Based on diagrams all will be done
Main diagrams are use-case, DFD and flow charts
USE-CASE
Have to define users and their tasks
Like website is college management system
Version 1.4
71. SDLC…
User is student having activities registration, login,
view & download assignments, view fees details, view
time table etc.
Can be shown in use-case as given below
Version 1.4
73. SDLC…
Once actions are defined, need to divide project in
modules
DFD is used for this
DFD – Data Flow Diagrams
Graphical representation of flow of data inside
application can also be used for visualization and data
processing
Version 1.4
74. SDLC…
DFD elements are..
External Entity
2. Process
3. Data Flow
4. Data Store
1.
Version 1.4
75. SDLC…
1.
External entity
Can be user or external system that performs some
process or activity in project
Symbolized with rectangle
Like, we have entity ‘admin’ then symbol will be
Admin
Version 1.4
76. SDLC…
2. Process
Work or action taken on incoming data to produce
output
Each process must have input and output
Symbolized as
1. Login
output
input
Version 1.4
77. SDLC…
3. Data Flow
Can be used to show input and output of data
Should be named uniquely and don’t include word
‘data’
Names can be ‘payment’, ‘order’, ’complaint’ etc
Symbolized as
Payment
Version 1.4
78. SDLC….
4. Data Store
Can be used to show database tables
Only process may connect data stores
There can be two or more process sharing same data
store
Symbolized as
Registration_Master
Version 1.4
79. DFD Rules…
6 rules to follow
Consider data flow diagram as given below
Version 1.4
81. Rule 1
Each process must have data flowing into it and
coming out from it
Version 1.4
82. Rule 2
Each data store must have data going inside and data
coming outside
Version 1.4
83. Rule 3
A data flow out of a process should have some relevance to
one or more of the data flows into a process
Version 1.4
84. Rule 3
In process 3 all data flows are connected to process
claim.
The claim decision can not be made until the claim
form has been submitted and the assessor makes a
recommendation
Version 1.4
85. Rule 4
Data stored in system must go through a process
Version 1.4
86. Rule 5
Two data stores can’t communicate with each other
unless process is involved in between
Version 1.4
87. Rule 6
The Process in DFD must be linked to either another
process or a data store
A process can’t be exist by itself, unconnected to rest of
the system
Version 1.4
89. Types of DFD…
Physical DFD
An implementation-dependent view of the current
system, showing what tasks are carried out and how
they are performed. Physical characteristics can
include:
Names of people
Form and document names or numbers
Equipment and devices used
Locations
Names of procedures
Version 1.4
90. Types Of DFD…
Logical Data Flow Diagrams
An implementation-independent view of the a system,
focusing on the flow of data between processes
without regard for the specific devices, storage
locations or people in the system. The physical
characteristics listed above for physical data flow
diagrams will not be specified.
Version 1.4
91. DFD Levels…
DFD level-0
It’s also context level DFD
Context level diagrams show all external entities.
They do not show any data stores.
The context diagram always has only one process
labeled 0.
Version 1.4
92. DFD Level-1(or 2)
include all entities and data stores that are directly
connected by data flow to the one process you are
breaking down
show all other data stores that are shared by the
processes in this breakdown
Like login process will linked to users & database in
further leveling
Version 1.4
97. Flow Charts…
Used to show algorithm or process
Can give step by step solution to the problem
The first flow chart was made by John Von Newman in
1945
Pictorial view of process
Helpful for beginner and programmers
Version 1.4
98. Flow Chart…
Flowcharts are generally drawn in the early stages of
formulating computer solutions.
Flowcharts facilitate communication between
programmers and business people.
These flowcharts play a vital role in the programming
of a problem and are quite helpful in understanding
the logic of complicated and lengthy problems.
Version 1.4
99. Flow Chart…
Once the flowchart is drawn, it becomes easy to write
the program in any high level language.
Often we see how flowcharts are helpful in explaining
the program to others.
Hence, it is correct to say that a flowchart is a must for
the better documentation of a complex program.
Version 1.4
100. Flow Chart…
Symbols are..
1.
Start Or End
Show starting or ending of any flow chart
Symbolized as
OR
Start
End
Version 1.4
101. Flow Charts…
2. Process
Defines a process like defining variables or initializing
variable or performing any computation
Symbolized as
res = num1 + num2
Version 1.4
102. Flow Charts…
3. Input or Output
Used when user have to get or initialize any variable
Like get num1 and num2 from user
Symbolized as
Int num1,num2
Version 1.4
103. Flow Charts…
4. Decision Making
For checking condition this symbols can be used
Like if num1 is greater than num2
Can be symbolized as
If num1>num2
Version 1.4
104. Flow Charts…
5. Flow lines
Lines showing flow of data and process
Showing flow of instructions also
Can be symbolized as
Version 1.4
105. Flow chart
Any program can be in three format
Linear or sequence
2. Branching
3. Looping
Following are notations can be used to show this
format
1.
Version 1.4
112. SDLC…
3. Designing
The Design document should reference what you are going to
build to meet the requirements, and not how it can include
pseudo code but shouldn’t contain actual code functionality.
Design elements describe the desired software features in
detail, and generally include functional hierarchy diagrams,
screen layout diagrams, tables of business rules, business
process diagrams, pseudo code, and a complete entityrelationship diagram with a full data dictionary.
These design elements are intended to describe the software
in sufficient detail that skilled programmers may develop the
software with minimal additional input. At this phase the test
plans are developed.
113. SDLC…
4. Implementation (Coding)
To launch the coding phase, develop a shell program that is
then put under some form of version control.
This phase includes the set up of a development environment,
and use of an enhanced editor for syntax checking.
114. SDLC…
5. Testing
Each developer insures that their code runs without warnings
or errors and produces the expected results.
The code is tested at various levels in software testing. Unit,
system and user acceptance tasting’s are often performed. This
is a grey area as many different opinions exist as to what the
stages of testing are and how much if any iteration occurs.
Types of testing: Defect testing, Path testing, Data set
testing, Unit testing, System testing, Integration testing,
Black box testing, White box testing, Regression testing,
Automation testing, User acceptance testing, Performance
testing, etc.
115. SDLC…
6. Maintenance
User’s guides and training are developed to reflect any new
functionality and changes which need to be identified to the
production staff.
Any changes needed to operations and/or maintenance need
to be addressed.
Every run in production needs to be verified. Any problems
with production need to be addressed immediately.
A Change Request system may be set up to allow for feedback
for enhancements.
118. What is Software Engineering?
The term software engineering first appeared in the 1968 NATO Software
Engineering Conference and was meant to provoke thought regarding the current
"software crisis" at the time.
Definition:“state of the art of developing quality software on
time and within budget”
•Trade-off between perfection and physical constraints
•SE has to deal with real-world issues
•State of the art!
•Community decides on “best practice”+ life-long education
120. Requirements
Collection
Establish Customer Needs
Analysis
Model And Specify the requirements-“What”
Design
Model And Specify a Solution –“Why”
Implementation
Construct a Solution In Software
Testing
Validate the solution against the requirements
Maintenance
Repair defects and adapt the solution to the new
requirements
121. Web Programming
WWW (World Wide Web)
Web addresses are URL (uniform resource locator)
A server address and a path to a particular file
URLs are often redirected to other places
http://students. -int.com/classes/PHP&MYSQL/index.html
protocol= http://
web server= students
domain= . -int.com
path= /classes/PHP&MYSQL/ (dirs(folders))
file= index.html
file extension= .html(hypertext markup language)
122. CLIENTS AND SERVERS
Web programming languages are usually classified as server-side or client-side. Some
languages, such as JavaScript, can be used as both client-side and server-side languages,
but most Web programming languages are server-side languages.
The client is the Web browser, so client-side scripting uses a Web browser to run scripts.
The same script may produce different effects when different browsers run it.
A Web server is a combination of software and hardware that outputs Web pages after
receiving a request from a client. Server-side scripting takes place on the server. If you
look at the source of a page created from a server-side script, you'll see only the HTML
code the script has generated. The source code for the script is on the server and doesn't
need to be downloaded with the page that's sent back to the client.
Web Programming Languages
PHP
ASP
Perl
JAVA
123. Client/Server Interaction
For Web pages, the client requests a page the server returns it:
there’s no permanent connection, just a short conversation
•Details of the conversation are specified by HTTP
124. Server-Side
PHP is a Server-side language
Even though it is embedded in HTML files much like the client-side JavaScript language,
PHP is server-side and all PHP tags will be replaced by the server before anything is sent
to the web browser.
•So if the HTML file contains:
<html>
<?php echo "Hello World"?>
</html>
•What the end user would see with a "view
source" in the browser would be:
<html>
Hello World
</html>
125. PHP Introduction
PHP can be installed on any web server: Apache, IIS, Netscape, etc…
PHP can be installed on any OS: Unix, Linux, Windows, MacOS, etc…
XAMPP is a free and open source cross-platform web server package, consisting mainly of
the Apache HTTP Server, MySQL database, and interpreters for scripts written in the
PHP and Perl programming languages.
It is used as a development tool, to allow website designers and programmers to test their
work on their own computers without any access to the Internet. .
XAMPP's name is an acronym for:
X (meaning cross-platform)
Apache HTTP Server
MySQL
PHP
Perl
LAMP package is used for Linux OS
WAMP package is used for Windows OS
126. PHP is a powerful server-side scripting language for creating dynamic
and interactive websites.
PHP is the widely-used, free, and efficient alternative to competitors
such as Microsoft's ASP. PHP is perfectly suited for Web development
and can be embedded directly into the HTML code.
The PHP syntax is very similar to Perl and C. PHP is often used
together with Apache (web server) on various operating systems. It also
supports ISAPI and can be used with Microsoft's IIS on Windows.
A PHP file may contain text, HTML tags and scripts. Scripts in a PHP
file are executed on the server.
What is a PHP File?
•PHP files may contain text, HTML tags and scripts
•PHP files are returned to the browser as plain HTML
•PHP files have a file extension of ".php", ".php3", or ".phtml"
127. What is PHP?
PHP stands for PHP: Hypertext Preprocessor
PHP is a server-side scripting language, like ASP
PHP scripts are executed on the server
PHP supports many databases (MySQL, Informix, Oracle, Sybase,
Solid, Postgre SQL, Generic ODBC, etc.)
PHP is an open source software (OSS)
PHP is free to download and use
Created in 1994
Syntax inherited from C, Java and Perl
Powerful, yet easy to learn
Why PHP?
PHP runs on different platforms (Windows, Linux, Unix, etc.)
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
PHP is FREE to download from the official PHP resource: www.php.net
PHP is easy to learn and runs efficiently on the server side
128. Diff Between php4 andphp5
There are several differences between PHP4 and
PHP5
1.Unified constructor and Destructor
2.Exception has been introduced
3.New error level named E_STRICT has been introduced
4.Now we can define full method definitions for a
abstract class
5.Within a class we can define class constants
6.we can use the final keyword to indicate that a method
cannot be overridden by a child
7.public, private and protected method introduced
8.Magic methods has been included
9.we can pass value by reference
129. How is PHP Used?
How is PHP used?
Content Management
Forums
Blogging
Wiki
CRM
131. HTML and CSS
HTML, which stands for Hyper Text Markup Language, is the predominant markup
language for web pages. It provides a means to create structured documents by denoting
structural semantics for text such as headings, paragraphs, lists etc as well as for links,
quotes, and other items. It allows images and objects to be embedded and can be used to
create interactive forms. It is written in the form of HTML elements consisting of "tags"
surrounded by angle brackets within the web page content. It can include or can
load scripts in languages such as JavaScript which affect the behavior of HTML
processors like Web browsers; and Cascading Style Sheets (CSS) to define the appearance
and layout of text and other material. The W3C, maintainer of both HTML and CSS
standards, encourages the use of CSS over explicit presentational markup
Hyper Text Markup Language (HTML) is the encoding scheme used to create and format
a web document. A user need not be an expert programmer to make use of HTML for
creating hypertext documents that can be put on the internet.
Example:<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
132. a language for describing the content and presentation of a
web page
content: The meaning and structure of the web page
•presentation: How the page is to be presented
HTML pages have a basic hierarchical structure defined by
the tags
<html>, <head>, <body>, and so on
Basic HTML describes a static page
once parsed and rendered, the page doesn’t change
hyper linking was the big step forward in basic HTML
133. Intro to HTML Forms
Types of input we can collect via forms:
Text via text boxes and text areas
Selections via radio buttons, check boxes, pull down
menus, and select boxes
Form actions do all of the work
Usually through button clicks
134. Basic HTML Form
<form name="input" action="form_action.php"
method="get">
<label for="user">Username</label>
<input type="text" name="user" id="user">
<br/><input type="submit" value="Submit">
</form>
139. Form Actions
<form name="input" action="html_form_action.php“
method="get">
Action specifies what file the form data will be sent to (on the
server)
Method specifies by which HTTP protocol
get
post
Method is important on the receiving end
140. PHP Forms And User Input
The PHP $_GET and $_POST variables are used to retrieve information
from forms, like user input.
PHP Form Handling
The most important thing to notice when dealing with HTML forms
and PHP is that any form element in an HTML page will automatically
be available to your PHP scripts.
Form example:
<html>
<body><form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form></body>
</html>
141. The example HTML page above contains two input fields and a submit button. When the
user fills in this form and click on the submit button, the form data is sent to the
"welcome.php" file.
•The "welcome.php" file looks like this:
<html>
<body>Welcome <?php echo $_POST["name"]; ?>.<br/>
You are <?php echo $_POST["age"]; ?> years old.</body>
</html>
A sample output of the above script may be:
Welcome John.
You are 28 years old.
Form Validation
User input should be validated whenever possible. Client side validation is faster, and will
reduce server load.
However, any site that gets enough traffic to worry about server resources, may also need
to worry about site security. You should always use server side validation if the form
accesses a database.
A good way to validate a form on the server is to post the form to itself, instead of
jumping to a different page. The user will then get the error messages on the same page as
the form. This makes it easier to discover the error.
142. PHP $_Get
The $_GET variable is used to collect values from a form with method="get".
The $_GET Variable
• The $_GET variable is an array of variable names and values sent by the HTTP GET
method.
• The $_GET variable is used to collect values from a form with method="get".
Information sent from a form with the GET method is visible to everyone (it will be
displayed in the browser's address bar) and it has limits on the amount of information to
send (max. 100 characters).
Example
<form action="welcome.php" method="get">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
When the user clicks the "Submit" button, the URL sent could look something like this:
http://www.-int.com/welcome.php?name=Peter&age=37
The "welcome.php" file can now use the $_GET variable to catch the form data (notice
that the names of the form fields will automatically be the ID keys in the $_GET array):
143. PHP $_Get
Welcome <?php echo $_GET["name"]; ?>.<br/>
You are <?php echo $_GET["age"]; ?> years old!
Why use $_GET?
Note: When using the $_GET variable all variable names
and values are displayed in the URL. So this method
should not be used when sending passwords or other
sensitive information! However, because the variables
are displayed in the URL, it is possible to bookmark the
page. This can be useful in some cases.
Note: The HTTP GET method is not suitable on
large variable values; the value cannot exceed 100
characters.
144. PHP $_Post
The $_POST variable is used to collect values from a form with method="post".
The $_POST Variable
The $_POST variable is an array of variable names and values sent by the HTTP POST
method.
The $_POST variable is used to collect values from a form with method="post".
Information sent from a form with the POST method is invisible to others and has no
limits on the amount of information to send.
Example
<form action="welcome.php" method="post">
Enter your name: <input type="text" name="name" />
Enter your age: <input type="text" name="age" />
<input type="submit" />
</form>
When the user clicks the "Submit" button, the URL will not contain any form data, and will look
something like this:
http://www.-int.com/welcome.php
The "welcome.php" file can now use the $_POST variable to catch the form data (notice that the
names of the form fields will automatically be the ID keys in the $_POST array):
Welcome <?php echo $_POST["name"]; ?>.<br/>
You are <?php echo $_POST["age"]; ?> years old!
145. PHP $_Post
Why use $_POST?
Variables sent with HTTP POST are not shown in the URL
Variables have no length limit
However, because the variables are not displayed in the URL, it is
not possible to bookmark the page.
The $_REQUEST Variable
The PHP $_REQUEST variable contains the contents of both
$_GET, $_POST, and $_COOKIE.
The PHP $_REQUEST variable can be used to get the result from
form data sent with both the GET and POST methods.
Example
Welcome <?php echo $_REQUEST["name"]; ?>.<br/>
You are <?php echo $_REQUEST["age"]; ?> years
old!
147. Introduction
Cascading Style Sheets (CSS).
With CSS you will be able to:
Add new looks to your old HTML
Completely restyle a web site with only a few changes
to your CSS code
Use the "style" you create on any web page you wish!
148. CSS Selector
SELECTOR { PROPERTY: VALUE }
HTML tag"{ "CSS Property": "Value" ; }
The selector name creates a direct relationship
with the HTML tag you want to edit. If you wanted
to change the way a paragraph tag behaved, the
CSS code would look like:
p { PROPERTY: VALUE }
The above example is a template that you can use
whenever you are manipulating the paragraph
HTML element
150. Creating Internal CSS Code
<head>
<style type="text/css">
p {color: white; }
body {background-color: black; }
</style>
</head>
<body>
<p>White text on a black background!</p>
</body>
We chose the HTML element we wanted to manipulate. -p{ : ; }
Then we chose the CSS attribute color. -p { color:; }
Next we choose the font color to be white. -p { color:white; }
Now all text within a paragraph tag will show up as white! Now an explanation of
the CSS code that altered the <body>'s background:
We choose the HTML element Body -body { : ; }
Then we chose the CSS attribute. -body { background-color:; }
•Next we chose the background color to be black. -body { backgroundcolor:black; }
151. External CSS
When using CSS it is preferable to keep the CSS
separate from your HTML. Placing CSS in a separate file
allows the web designer to completely differentiate
between content (HTML) and design (CSS). External
CSS is a file that contains only CSS code and is saved
with a ".css" file extension. This CSS file is then
referenced in your HTML using the <link> instead of
<style>.
body{ background-color: gray }
p { color: blue; }
h3{ color: white; }
Save it as .css
152. HTML
<html>
<head>
<link rel="stylesheet" type="text/css“ href="test.css" />
</head>
<body>
<h3> A White Header </h3>
<p> This paragraph has a blue font. The background color
of this page is gray because we changed it with CSS!
</p>
</body>
</html>
153. Inline css
It is possible to place CSS right in the thick of your
HTML code, and this method of CSS usage is
referred to as inline css.
Inline CSS has the highest priority out of external,
internal, and inline CSS. This means that you can
override styles that are defined in external or
internal by using inline CSS
<p style="background: blue; color: white;">
A new background and font color with inline CSS
</p>
154. Property value of css
A value is given to the property following a colon (NOT an 'equals' sign)
and semi-colons separate the properties.
body {font-size: 0.8em;color: navy;}
This will apply the given values to the font-size and color properties to
the body selector.
So basically, when this is applied to an HTML document, text between
the body tags (which is the content of the whole window) will be
0.8emsin size and navy in colour.
em (such as font-size: 2em) is the unit for the calculated size of a font.
So "2em", for example, is two times the current font size.
px(such as font-size: 12px) is the unit for pixels.
pt (such as font-size: 12pt) is the unit for points.
% (such as font-size: 80%) is the unit for... wait for it... percentages.
155. Text property
font-family
This is the font itself, such as Times New Roman, Arial, or Verdana.
font-family: "Times New Roman".
font-size
font-weight
This states whether the text is bold or not.
font-style
This states whether the text is italic or not. It can be font-style: italic or font-style:
normal.
text-decoration
This states whether the text is underlined or not. This can be:
text-decoration: overline, which places a line above the text.
text-decoration: line-through, strike-through, which puts a line through the text.
text-decoration: underline should only be used for links because users
generally expect underlined text to be links.
This property is usually used to decorate links, such as specifying no underline with
text-decoration: none.
Letter Spacing:3px
156. text-transform
This will change the case of the text.
text-transform: capitalize turns the first letter of every
word into uppercase.
text-transform: uppercase turns everything into
uppercase.
text-transform: lowercase turns everything into
lowercase.
text-transform: none I'll leave for you to work out.
157. Margins and Padding
Margin and padding are the two most commonly used properties for
spacing-out elements. A margin is the space outside of the element,
whereas padding is the space inside the element
The four sides of an element can also be set individually. margin-top,
margin-right, margin-bottom, margin-left, padding-top,
padding-right, padding-bottom and padding-left are the selfexplanatory properties you can use.
158. CSS Classes
It is possible to give an HTML element multiple looks with CSS.
The Format of Classes
Using classes is simple. You just need to add an extension to the typical
CSS code and make sure you specify this extension in your HTML. Let's
try this with an example of making two paragraphs that behave
differently. First, we begin with the CSS code, note the red text.
CSS Code: p. first{ color: blue; } p.second{ color: red; } HTML Code:
<html>
<body>
<p>This is a normal paragraph.</p>
<p class="first">This is a paragraph that uses the p. first CSS code!</p>
<p class="second">This is a paragraph that uses the p. second CSS
code!</p> ...
159. CSS Background
The background of website is very important
With CSS, you are able to set the background color or image of any CSS
element. In addition, you have control over how the background image is
displayed. You may choose to have it repeat horizontally, vertically, or in
neither direction. You may also choose to have the background remain in a
fixed position, or have it scroll as it does normally.
CSS Background Color
Varying backgrounds were obtained without using tables! Below are a couple
examples of CSS backgrounds.
CSS Code:
h4 { background-color: white; } p { background-color: #1078E1; } ul {
background-color:rgb( 149, 206, 145); }
160. CSS Background Image
Need an image to repeat left-to-right, like the gradient
background
you would like to have an image that remains fixed when
the user scrolls down your page. This can be done quite
easily with CSS and more, including:
choosing if a background will repeat and which directions
to repeat in.
precision positioning scrolling/static images
CSS Code:
p { background-image:url(smallPic.jpg); } h4{ backgroundimage:url(http://www.tizag.com/pics/cssT/smallPic.jpg); }
163. CSS Background
CSS Gradient Background
If you would like to create a gradient background like the one that
appears at the top of Tizag.com, you must first create an image inside a
painting program (Photoshop, Draw, etc) like the one you see below.
p { background-image:url(http://www./gradient.gif);
background-repeat: repeat-x; }
164. CSS Links ( Pseudo-classes )
Anchor/Link States
link-this is a link that has not been used, nor is a mouse pointer
hovering over it
visited-this is a link that has been used before, but has no mouse on it
hover-this is a link currently has a mouse pointer hovering over it/on it
active-this is a link that is in the process of being clicked
170. With cascading style sheets, there are a number of ways you can apply styles
to text.
1)One way is to use inline style definitions. These allow you to specify
styles in the style attribute of any HTML tag.
2)Second way is to use a style sheet specified in the header of your document.
You can then refer to and reuse these styles throughout your document.
A document style sheet is specified between opening and closing style tags in
the header of your document:
<head>
<style type=”text/css”>
</style>
</head>
To build your style sheet, just define the styles in the style block. You can define
three types of style definitions:
HTML element definitions, which specify a default style for different
HTML elements (in other words, for different HTML tags)
Class definitions, which can be applied to any HTML tag by using
the class attribute common to all tags
Identity definitions, which apply to any page elements that have a
matching ID
171. The following steps show you how to create a style sheet in a document and then
use the styles:
1. In the header of a new document, create a style block:
<style type=”text/css”>
</style>
2. In the style block, create a style definition for the p tag:
P{
font-family: Arial, Helvetica, SANS-SERIF;
color: #ff0000; }
3. Next, create a style definition for the my Class class:
.myClass{
font-size: 24pt;
font-style: italic; }
4. Finally, create a style definition for elements with the my IDID:
#myID{ background-color: #cccccc; }
5. In the body of your document, create a level 1 heading and apply the
My Class class to it:
<h1 class=”myClass”> This is a headline </h1>
172. CSS Pseudo-classes
css anchor/link states
You may not know it, but a link has four different states that it can be in. CSS allows you to customize
each state. Please refer to the following keywords that each correspond to one specific state:
link - this is a link that has not been used, nor is a mouse pointer hovering over it
visited - this is a link that has been used before, but has no mouse on it
hover - this is a link currently has a mouse pointer hovering over it/on it
active - this is a link that is in the process of being clicked
Using CSS you can make a different look for each one of these states, but at the end of this lesson we
will suggest a good practice for CSS Links.
174. CSS pseudo –class
Syntax
The syntax of pseudo-classes:
selector:pseudo-class {property:value}
CSS classes can also be used with pseudo-classes:
selector.class:pseudo-class {property:value}
Example
Specify the color of links:
a:link {color:#FF0000}
/* unvisited link */
a:visited {color:#00FF00} /* visited link */
a:hover {color:#FF00FF} /* mouse over link */
a:active {color:#0000FF} /* selected link */
175. CSS - The :first-child Pseudo-class
Match the first <p> element
In the following example, the selector matches any <p> element that is the first child of any element:
Example
<html>
<head>
<style type="text/css">
p:first-child
{
color:blue
}
</style>
</head>
<body>
<p>I am a strong man.</p>
<p>I am a strong man.</p>
</body>
</html>
176. Match the first <i> element in all <p>
elements
Example
<html>
<head>
<style type="text/css">
p > i:first-child
{
font-weight:bold
}
</style>
</head>
<body>
<p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p>
<p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p>
</body>
</html>
177. Match all <i> elements in all first child <p>
elements
<html>
<head>
<style type="text/css">
p:first-child i
{
color:blue
}
</style>
</head>
<body>
<p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p>
<p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p>
</body>
</html>
178. CSS - The :lang Pseudo-class
<html>
<head>
<style type="text/css">
q:lang(no) {quotes: "~" "~"}
</style>
</head>
<body>
<p>Some text <q lang="no">A quote in a paragraph</q> Some
text.</p>
</body>
</html>
179. The :first-line/letter Pseudo-element
Pseudo-elements can be combined with CSS classes:
Example:p.article:first-letter
{color:#ff0000
}
<p class="article">A paragraph in an article</p>
p:first-letter
{
color:#ff0000;
font-size:xx-large;
}
p:first-line
{
color:#0000ff;
font-variant:small-caps;
}
184. PHP as a Scripting Language
PHP, or PHP: Hypertext Preprocessor, is a widely used, general-
purpose scripting language that was originally designed for web
development, to produce dynamic web pages. It can be embedded
into HTML and generally runs on a web server, which needs to be
configured to process PHP code and create web page content from it. It
can be deployed on most web servers and on almost every operating
system and platform free of charge. PHP is installed on over 20 million
websites and 1 million web servers
PHP was originally created by Rasmus Lerdorf in 1995 and has been in
continuous development ever since. The main implementation of PHP
is now produced by The PHP Group and serves as the de
facto standard for PHP as there is no formal specification. PHP is free
software released under the PHP License, which is incompatible with
the GNU General Public License (GPL) because of restrictions on the
use of the term PHP.
185. PHP Syntax
Below, we have an example of a simple PHP script which sends the text
"Hello World" to the browser:
<html>
<body><?php
echo "Hello World";
?></body>
</html>
Each code line in PHP must end with a semicolon. The semicolon is a
separator and is used to distinguish one set of instructions from
another.
There are two basic statements to output text with PHP: echo and
print. In the example above we have used the echo statement to output
the text "Hello World".
186. PHP Syntax
Comments in PHP
•In PHP, we use // to
make a single-line
comment or /* and
*/ to make a large
comment block.
<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
*/
?>
</body>
</html>
187. PHP Variables
Variables are used for storing values, such as numbers, strings or
function results, so that they can be used many times in a script.
Variables in PHP
Variables are used for storing a values, like text strings, numbers or
arrays.
When a variable is set it can be used over and over again in your script
All variables in PHP start with a $ sign symbol.
The correct way of setting a variable in PHP:
$var_name = value; New PHP programmers often forget the $ sign at
the beginning of the variable. In that case it will not work.
Let's try creating a variable with a string, and a variable with a number:
<?php
$txt = "Hello World!";
$number = 16;
?>
188. Names (also called identifiers)
Must always begin with a dollar-sign ($)
generally start with a letter and can contain letters,
numbers, and underscore characters “_”
Names are case sensitive
Values can be numbers, strings, boolean, etc
change as the program executes
189. PHP is a Loosely Typed Language
In PHP a variable does not need to be declared before
being set.
In the example above, you see that you do not have to tell
PHP which data type the variable is.
PHP automatically converts the variable to the correct data
type, depending on how they are set.
In a strongly typed programming language, you have to
declare (define) the type and name of the variable before
using it.
In PHP the variable is declared automatically when you use
it.
191. Variables and Expressions in PHP
Names (also called identifiers)
Must always begin with a dollar-sign ($)
generally start with a letter and can contain letters, numbers, and underscore characters
“_”
Names are case sensitive
Values can be numbers, strings, boolean, etc
change as the program executes
Expressions are the most important building stones of PHP. In PHP,
almost anything you write is an expression. The simplest yet most
accurate way to define an expression is "anything that has a value".
192.
There is one more expression that may seem odd if you haven't seen it in other languages, the ternary
conditional operator:
<?php
$first ? $second : $third
?>
If the value of the first subexpression is TRUE (non-zero), then the second subexpression is
evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is
evaluated, and that is the value.
The following example should help you understand pre- and post-increment and expressions in
general a bit better:
<?php
function double($i)
{
return $i*2;
}
$b = $a = 5;
/* assign the value five into the variable $a and $b */
$c = $a++;
/* post-increment, assign original value of $a (5) to $c */
$e = $d = ++$b; /* pre-increment, assign the incremented value of $b (6) to $d and $e */
/* at this point, both $d and $e are equal to 6 */
$f = double($d++); /* assign twice the value of $d before the increment, 2*6 = 12 to $f */
$g = double(++$e); /* assign twice the value of $e after the increment, 2*7 = 14 to $g */
$h = $g += 10; /* first, $g is incremented by 10 and ends with the value of 24. the value of the
assignment (24) is then assigned into $h, and $h ends with the value of 24 as
well. */
?>
193. PHP Operators
c=a+b
Assuming a and b are numbers (remember data types? --
the result would be different if they were strings -- more
about that later) this expression would add a and b and put
the sum into c (remember again, that the equals sign here
makes this an assignment instruction.) In the expression a
+ b the plus sign is an arithmetic operator. Here are some
more operators:
Arithmetic Operators:
Comparison Operators:
Logical Operators:
Increment and Decrement Operators:
The Concatenate Operator
Combined Operators:
194. PHP Operators
Operators are used to operate on values.
PHP Operators
This section lists the different operators used in PHP.
Arithmetic Operators
197. Conditional Test, Events and Flows in PHP
PHP If & Else Statements
The if, elseif and else statements in PHP are used to perform
different actions based on different conditions.
Conditional Statements
Very often when you write code, you want to perform different
actions for different decisions.
You can use conditional statements in your code to do this.
if...else statement -use this statement if you want to
execute a set of code when a condition is true and
another if the condition is not true
elseif statement -is used with the if...else statement to
execute a set of code if one of several condition are
true
198. PHP If & Else Statements
The If...Else Statement
If you want to execute some code if a condition is true and another code if a condition is
false, use the if....else statement.
Example
The following example will output "Have a nice weekend!" if the current day is Friday, otherwise
it will output "Have a nice day!":
<html>
<body><?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
echo "Have a nice day!";
else
?></body>
</html>
199. PHP If & Else Statements
If more than one line should be executed if a condition is
true/false, the lines should be enclosed within curly braces:
<html>
<body><?php
$d=date("D");
if ($d=="Fri")
{
echo "Hello!<br/>";
echo "Have a nice weekend!";
echo "See you on Monday!";
}
?></body>
</html>
200. PHP If & Else Statements
The ElseIf Statement
If you want to execute some code if one of several
conditions are true use the elseif statement
Syntax
if (condition)
code to be executed if condition is true;
elseif(condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
201. PHP If & Else Statements
Example
The following example will output "Have a nice weekend!" if the
current day is Friday, and "Have a nice Sunday!" if the current day is
Sunday. Otherwise it will output "Have a nice day!":
<html>
<body><?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
elseif($d=="Sun")
echo "Have a nice Sunday!";
Else
echo "Have a nice day!";
?></body>
</html>
202. PHP Switch Statement
•The Switch statement in PHP is used to perform one of several different
actions based on one of several different conditions.
The Switch Statement
•If you want to select one of many blocks of code to be executed, use the Switch
statement.
•The switch statement is used to avoid long blocks of if..elseif..else code.
Syntax
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed
if expression is different
from both label1 and label2;
}
203. PHP Switch Statement
Example
This is how it works:
A single expression (most often a variable) is evaluated once
The value of the expression is compared with the values for each case in the
structure
If there is a match, the code associated with that case is executed
After a code is executed, break is used to stop the code from running into the next
case
The default statement is used if none of the cases are true
<html>
<body><?php
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
}
?></body>
</html>
204. Iteration
Iteration or looping is a way to execute a block of program
statements more than once
we will use the for statement to create loops
The for loop is generally controlled by counting
There is an index variable that you increment or decrement
each time through the loop
When the index reaches some limit condition, then the
looping is done and we continue on in the code
205. Why do we want loops in our code?
• Do something for a given number of times or for
every object in a collection of objects
for every radio button in a form, see if it is checked
for every month of the year, charge $100 against the
balance
calculate the sum of all the numbers in a list
Many loops are counting loops
they do something a certain number of times
206.
207.
208.
209. PHP Looping
Looping statements in PHP are used to execute the same block of code a
specified number of times.
Looping
Very often when you write code, you want the same block of code to
run a number of times. You can use looping statements in your code to
perform this.
In PHP we have the following looping statements:
while -loops through a block of code if and as long as a specified
condition is true
do...while -loops through a block of code once, and then repeats the
loop as long as a special condition is true
for -loops through a block of code a specified number of times
foreach-loops through a block of code for each element in an array
210. PHP Looping
The while Statement
The while statement will execute a block of code if and as long as a condition is true.
Syntax
while (condition)
code to be executed;
Example
The following example demonstrates a loop that will continue to run as long as the
variable i is less than, or equal to 5. i will increase by 1 each time the loop runs:
<html>
<body><?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br/>";
$i++;
}
?></body>
</html>
211. PHP Looping
The do...while Statement
•The do...while statement will execute a block of code at least once-it then will repeat the loop as long as a
condition is true.
Syntax
do
{
code to be executed;
}
while (condition);
Example
The following example will increment the value of i at least once, and it will continue incrementing
the variable i as long as it has a value of less than 5:
<html>
<body><?php
$i=0;
do
{
$i++;
echo "The number is " . $i . "<br/>";
}
while ($i<5);
?></body>
</html>
212. PHP Looping
The for Statement
•The for statement is used when you know how many times you want to execute a statement or a list of statements.
Syntax
for (initialization; condition; increment)
{
code to be executed;
}
Note: The for statement has three parameters. The first parameter initializes variables, the
second parameter holds the condition, and the third parameter contains the increments
required to implement the loop. If more than one variable is included in the initialization
or the increment parameter, they should be separated by commas. The condition must
evaluate to true or false.
Example
The following example prints the text "Hello World!" five times:
<html>
<body><?php
for ($i=1; $i<=5; $i++)
{
echo "Hello World!<br/>";
}
?></body>
</html>
213. PHP Looping
The foreach Statement
The for each statement is used to loop through arrays.
For every loop, the value of the current array element is assigned to $value (and the
array pointer is moved by one) -so on the next loop, you'll be looking at the next
element.
Syntax
foreach(array as value)
{
code to be executed;
}
Example
The following example demonstrates a loop that will print the values of the given
array:
<html>
<body><?php
$arr=array("one", "two", "three");
foreach($arras $value)
{
echo "Value: " . $value . "<br/>";
}
?></body>
</html>
214. Project Based Lab
Prepare a flowchart and DFD of the project whichever is assign to you
..
Flowchart indicate the workflow of the system.
A data flow diagram (DFD) is a graphical representation of the "flow" of
data through an information system. It differs from the flowchart as it
shows the data flow instead of the control flow of the program.
215. Difference between echo and print
1. Speed. There is a difference between the two, but speed-wise it
should be irrelevant which one you use. echo is marginally faster
2. Expression. print() behaves like a function in that you can do:
$ret = print "Hello World"; And $ret will be 1. That means that print
can be used as part of a more complex expression where echo
cannot.
An example from the PHP Manual:
$b ? print "true" : print "false";
216. 3. Parameter(s). The grammar is: echo expression [,
expression[,expression] ... ] But echo ( expression, expression ) is not
valid.
This would be valid: echo ("howdy"),("partner"); the same as: echo
"howdy","partner";
So, echo without parentheses can take multiple parameters, which get
concatenated:
echo "and a ", 1, 2, 3; // comma-separated without parentheses
echo ("and a 123"); // just one parameter with parentheses
print() can only take one parameter:
print ("and a 123");
print "and a 123";
218. PHP Functions
The real power of PHP comes from its functions.
In PHP -there are more than 700 built-in functions available.
Create a PHP Function
A function is a block of code that can be executed whenever we need it.
Creating PHP functions:
All functions start with the word "function()"
Name the function -It should be possible to understand what the
function does by its name. The name can start with a letter or
underscore (not a number)
Add a "{"-The function code starts after the opening curly brace
Insert the function code
Add a "}"-The function is finished by a closing curly brace
219. PHP Functions
Example
•A simple function that writes my name when it is called:
<html>
<body><?php
Function writeMyName()
{
echo "Kai JimRefsnes";
}
writeMyName();
?></body>
</html>
Use a PHP Function
•Now we will use the function in a PHP script:
<html>
<body><?php
function writeMyName()
{
echo "Kai JimRefsnes";
}
echo "Hello world!<br/>";
echo "My name is ";
writeMyName();
echo ".<br/>That's right, ";
writeMyName();
echo " is my name.";
?></body>
</html>
220. PHP Functions
The output of the code above will be:
Hello world!
My name is Kai JimRefsnes.
That's right, Kai JimRefsnes is my name.
PHP Functions -Adding parameters
•Our first function (writeMyName()) is a very simple function. It only writes a static string.
•To add more functionality to a function, we can add parameters. A parameter is just like a variable.
•You may have noticed the parentheses after the function name, like: writeMyName(). The parameters
are specified inside the parentheses.
Example 1
•The following example will write different first names, but the same last name:
<html>
<body><?php
function writeMyName($fname)
{
echo $fname. "Refsnes.<br/>";
}
echo "My name is ";
writeMyName("Kai Jim");echo "My name is ";
writeMyName("Hege");echo "My name is ";
writeMyName("Stale");
?></body>
221. PHP Functions
•The output of the code above will be:
My name is Kai JimRefsnes.
My name is Hege Refsnes.
My name is Stale Refsnes.
Example 2
•The following function has two parameters:
<html>
<body><?php
function writeMyName($fname,$punctuation)
{
echo $fname. "Refsnes" . $punctuation . "<br/>";
}
echo "My name is ";
writeMyName("Kai Jim",".");
echo "My name is ";
writeMyName("Hege","!");
echo "My name is ";
writeMyName("Ståle","...");
?></body>
</html>
222. PHP Functions
•The output of the code above will be:
My name is Kai Jim Refsnes.
My name is Hege Refsnes!
My name is Ståle Refsnes...
PHP Functions -Return values
•Functions can also be used to return values.
Example
<html>
<body><?php
function add($x,$y)
{
$total = $x + $y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?></body>
</html>
The output of the code above will be:
1 + 16 = 17
229. PHP Date()
PHP Date -Format the Date
•The first parameter in the date() function specifies how to format the date/time. It uses
letters to represent date and time formats. Here are some of the letters that can be
used:
•d -The day of the month (01-31)
•m -The current month, as a number (01-12)
•Y -The current year in four digits
Other characters, like"/", ".", or "-" can also be inserted between the letters to add
additional formatting:
<?php
echo date("Y/m/d");
echo "<br/>";
echo date("Y.m.d");
echo "<br/>";
echo date("Y-m-d");
?>
The output of the code above could be something like this:
2009/07/11
2009.07.11
2009-07-11
230. PHP Date()
PHP Date -Adding a Timestamp
•The second parameter in the date() function specifies a timestamp. This
parameter is optional. If you do not supply a timestamp, the current time
will be used.
•In our next example we will use the mktime() function to create a timestamp
for tomorrow.
•The mktime() function returns the Unix timestamp for a specified date.
Syntax
•mktime(hour,minute,second,month,day,year,is_dst)
•To go one day in the future we simply add one to the day argument of
mktime():
<?php
$tomorrow =mktime(0,0,0,date("m"),date("d")+1,date("Y"));
echo "Tomorrow is ".date("Y/m/d", $tomorrow);
?>
The output of the code above could be something like this:
Tomorrow is 2006/07/12
231. PHP Arrays
• An array can store one or more values in a single variable name.
What is an array?
• When working with PHP, sooner or later, you might want to create many similar
variables.
• Instead of having many similar variables, you can store the data as elements in
an array.
• Each element in the array has its own ID so that it can be easily accessed.
• There are three different kind of arrays:
• Numeric array -An array with a numeric ID key
• Associative array -An array where each ID key is associated with a value
• Multidimensional array -An array containing one or more arrays
Numeric Arrays
• A numeric array stores each element with a numeric ID key.
• There are different ways to create a numeric array.
Example 1
• In this example the ID key is automatically assigned:
$names = array("Peter","Quagmire","Joe");
232. PHP Arrays
Example 2
• In this example we assign the ID key manually:
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";
•The ID keys can be used in a script:
<?php
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";
echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbors";
?>
•The code above will output:
Quagmire and Joe are Peter's neighbors
233. PHP Arrays
Associative Arrays
•An associative array, each ID key is associated with a value.
•When storing data about specific named values, a numerical array is not always the best way to do
it.
•With associative arrays we can use the values as keys and assign values to them.
Example 1
•In this example we use an array to assign ages to the different persons:
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
Example 2
This example is the same as example 1, but shows a different way of creating the array:
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
<?php
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
echo "Peter is " . $ages['Peter'] . " years old.";
?>
The code above will output:
Peter is 32 years old.
234. PHP Arrays
Multidimensional Arrays
•In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array
can be an array, and so on.
Example
•In this example we create a multidimensional array, with automatically assigned ID keys:
$families = array
(
"Griffin"=>array
(
"Peter",
"Lois",
"Megan"
),
"Quagmire"=>array
(
"Glenn"
),
"Brown"=>array
(
"Cleveland",
"Loretta",
"Junior"
)
);
235. PHP Arrays
•The array above would look like this if written to the output:
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
)
236. Commonly used Array Functions
array_combine --Creates an array by using one array for keys and
another for its values
array_count_values --Counts all the values of an array
Array_diff -Computes the difference of arrays
Array_merge -Merge one or more arrays
Array_merge_recursive -Merge two or more arrays recursively
Array_reverse -Return an array with elements in reverse order
Array_search -Searches the array for a given value and returns the
corresponding key if successful
Array_sum -Calculate the sum of values in an array
Arsort-Sort an array in reverse order and maintain index association
Asort-Sort an array and maintain index association
Krsort-Sort an array by key in reverse order
Ksort-Sort an array by key
sizeof-
244. PHP Arrays
Example 2
Lets try displaying a single value from the array above:
echo "Is " . $families['Griffin'][2] .
" a part of the Griffin family?";
The code above will output:
Is Megan a part of the Griffin family?
245. PHP Include File
• Server Side Includes (SSI) are used to create functions, headers, s, or elements
that will be reused on multiple pages.
Server Side Includes
•You can insert the content of a file into a PHP file before the server executes it,
with the include() or require() function. The two functions are identical in
every way, except how they handle errors. The include() function generates a
warning (but the script will continue execution) while the require() function
generates a fatal error (and the script execution will stop after the error).
•These two functions are used to create functions, headers, s, or elements that can
be reused on multiple pages.
•This can save the developer a considerable amount of time. This means that you
can create a standard header or menu file that you want all your web pages to
include. When the header needs to be updated, you can only update this one
include file, or when you add a new page to your site, you can simply change the
menu file (instead of updating the links on all web pages).
246. • Include_once and require_once is also use for include any file into your code.
• But the difference between include and include_once is in include if there is any
error in include file there is no effect on the code where it is included but in
include_once there is effect in the code if there is any error.
247. PHP Include File
The include() Function
•The include() function takes all the text in a specified file and copies it into the file that uses the include function.
Example 1
•Assume that you have a standard header file, called "header.php". To include the header file in a page, use the include() function, like this:
<html>
<body>
<?phpinclude("header.php"); ?>
<h1>Welcome to my home page</h1>
<p>Some text</p>
</body>
</html>
Example 2
Now, let's assume we have a standard menu file that should be used on all pages (include files usually have a ".php" extension). Look at the
"menu.php" file below:
<html>
<body>
<ahref="http://www.example.com/default.php">Home</a> |
<ahref="http://www. example.com/about.php">About Us</a> |
<ahref="http://www. example.com/contact.php">Contact Us</a>
The three files, "default.php", "about.php", and "contact.php" should all include the "menu.php" file. Here is the code in "default.php":
<?phpinclude("menu.php"); ?>
<h1>Welcome to my home page</h1>
<p>Some text</p>
</body>
</html>
248. PHP Include File
If you look at the source code of the "default.php" in a browser, it will look
something like this:
<html>
<body>
<ahref="default.php">Home</a> |
<ahref="about.php">About Us</a> |
<ahref="contact.php">Contact Us</a>
<h1>Welcome to my home page</h1>
<p>Some text</p>
</body>
</html>
• And, of course, we would have to do the same thing for "about.php"
and "contact.php". By using include files, you simply have to update
the text in the "menu.php" file if you decide to rename or change the
order of the links or add another web page to the site.
249. PHP Include File
The require() Function
•The require() function is identical to include(), except that it handles errors differently.
•The include() function generates a warning (but the script will continue execution) while the require() function
generates a fatal error (and the script execution will stop after the error).
•If you include a file with the include() function and an error occurs, you might get an error message like the one
below.
PHP code:
•<html>
•<body>
•<?php
•include("wrongFile.php");
•echo "Hello World!";
•?>
•</body>
•</html>
Error message:
Warning:include(wrongFile.php) [function.include]:
failed to open stream:
No such file or directory in C:homewebsitetest.phpon line 5
Warning:include() [function.include]:
Failed opening'wrongFile.php'for inclusion
(include_path='.;C:php5pear')
in C:homewebsitetest.phpon line 5
Hello World!
250. PHP Include File
• The echo statement was not executed because the script
execution stopped after the fatal error.
• It is recommended to use the require() function instead of
include(), because scripts should not continue executing if
files are missing or misnamed.
251. HTTP Overview
HTTP is the protocol (the set of 'rules') for transferring data (e.g.
HTML in web pages, pictures, files) between web servers and client
browsers, and usually takes place on port80. This is where the 'http://'
in website URLs comes from.
Headers can be separated into two broad types: Request the headers
that your browser sends to the server when you request a file, and
Response headers that the server sends to the browser when it serves
the file.
PHP header(): The Basics
Using this function, you can make your scripts send headers of
your choosing to the browser, and create some very useful and
dynamic results. However, the first thing you need to know about
the header() function is that you have to use it before PHP has
sent any output (and therefore its default headers).
252.
253.
PHP header(): Some Examples
header('Location:http://www.mysite.com/new_location.html');
While you can sometimes get away with supplying a relative URL for the value, according to
the HTTP specification, you should really use an absolute URL.
One mistake that is easy to make with the Location header is not calling exit directly
afterwards (you may not always want to do this, but usually you do). The reason this is a
mistake is that the PHP code of the page continues to execute even though the user has gone
to a new location. In the best case, this uses system resources unnecessarily. In the worst
case, you may perform tasks that you never meant to.
<?php
header('Refresh:10;url=http://www.mysite.com/otherpage.php');
echo'Youwillberedirectedin10seconds';
?>
Redirecting with the Refresh header
The Refresh redirects users like the Location header does, but you can add a delay before the
user is redirected. For example, the following code would redirect the user to a new page after
displaying the current one for 10 seconds
254. Serving different types of files and generating dynamic
content using the Content-Type header
The Content-Type header tells the browser what type of data the server is about
to send. Using this header, you can have your PHP scripts output anything from
plaintext files to images or zip files. The table below lists frequently-used
MIME types:
<?php
header'Connt-Type:text/plain');
Echo $lain_text_content;
?>
You can do several interesting things with this. For example, perhaps you want
to send the user a pre-formatted text file rather than HTML:
<?php
header('Content-Type:application/octet-stream'); // name of the File Name
header('Content-Disposition: attachment; '.'filename="plain_text_file.txt"'); // given name and with MIME type.
echo $plain_text_content;
?>
Or perhaps you'd like to prompt the user to download the file, rather
than viewing it in the browser. With the help of the ContentDisposition header, it's easy to do, and you can even suggest a file name
for the user to use: