Vous êtes sur la page 1sur 62

What is PHP?

PHP:

stands for Hypertext Pre-processor

is a server-side scripting language

supports many different databases

is an open source software

Apart from the normal text and HTML tags placed in a web page, a PHP file cont ains
commands that are executed on the server side. The server executes these commands before it
renders the response page to the user.
When a URL is typed on the browser for a PHP page, the following occurs

A request is sent to the browser requesting for that page

The server executes the PHP scripts on that file if any and sends the response to the
browser

The browser executes the HTML tags in that page and renders the response to the end
user

Support for Database

A Web Application normally requires data to be made persistent for accessing and
manipulating it in the future.
A typical web application scenario would be an Online Shopping Cart application,
which maintains its customers information and allows them to shop products online.
PHP supports many databases like MYSQL, Oracle, Sybase, Informix, etc.

runs on many different operating system platforms (Windows, Linux, Unix, etc.)

is compatible with almost all servers available and used today (Apache, IIS, etc.)

is free of cost and can be downloaded from the official PHP resource: www.php.net

is an open source software where we are free to add or modify the features of the s
oftware syntax is based on programming languages like C and PERL.

is easy to learn and it runs efficiently on the server side

Basic Syntax of PHP

PHP file normally contains HTML tags and PHP Scripting tags
PHP Scripting Elements should be enclosed within
<?php
?>
Example1.1: Display a Message in the Web Browser
<?php
echoWelcome to PHP Programming!!!!
?>

Php Statement terminator and Case insensitivity

Every Statement in PHP has to be terminated by a semicolon


<?php
echo "PHP Learning time";
echo "All statements have to be terminated by a semicolon(;)";
?>

PHP keywords and function names are case insensitive


The following statements convey the same meaning to the PHP interpreter
echo strlen("hello");
echo STRLEN("hello");
ECHO strLEN("hello");

Embedding PHP in HTML

A PHP code can be embedded in HTML using the PHP Scripting block <?php ?>
<html>
<font color="red">
<?php echo "PHP is a HTML embedded scripting language ";
echo "<br>"
</font>
</html>
The message will be displayed on the Web Browser in Red.
Alternatively a PHP scripting block can also include the HTML tag enclosed within quotes
(single or double)
<html>
<font color="red">
<?php
echo "PHP is a HTML embedded scripting language";
echo "<br>";
echo "It is used to create dynamic web pages";
?>
</font>
</html>
There can be multiple PHP Blocks within the same file. The above code can also be written
as
<html>
<font color="red>
<?php
echo "PHP is a HTML embedded scripting language";
?>
<br/>
<?php
echo "It is used to create dynamic web pages";
?>
</font>
</html>

Comments

Comments are used to explain the code and make it more readable. The PHP interpreter
generally ignores comments.
PHP supports 2 types of comments

Single line comment - //


//Comments can be short and crisp.

Multi line comment - /* */

/*
This is a Multi Line Comment.
-Can be used if explanation requires more than one line
-Can be used to temporarily turn off a block of code
*/

Variables
Variables are used to store data that is manipulated throughout the program. All Variables in
PHP have to be declared using the $ symbol
Syntax for declaring a variable
$variablenam e= value

Variables in PHP need not be declared for assigning a value to it

Variables in PHP are not ass ociated with a particular data type

PHP variables are associated with the data type depending on the value assigned to it
from time to time

Rules for Declaring a Variable


A variable name:

must start with a letter of the alphabet or an underscore "_"

can contain alpha numeric characters (a-z, A-Z, 0-9, and _)

should not contain spaces.

Assigning value to a variable


$country=India;
$order_no=122;
$course_fee=20754.75
Illegal Variable names
$+23
$12
$1ABC
Example1.2 Calculating area of a circle
<html>
<body>
<font face="arial">
<h3><b><i>Calculate Area of Circle</i></b></h3> <?php
$PI=3.14;
$area=0;
?>
<?php
$radius=3;
$area=$PI*$radius*$radius;
print "PI Value:".$PI."<br>";
print "Radius Value:".$radius."<br>";
print "Area Of Circle(PI*radius*radius) :".$area;
?>
</font>
</body>
</html>
Output on the Web Browser

Indirect reference to Variables


PHP helps us to create variables and access them by name at run time

Example 1.3: Print message to welcome the user


<?php
$name="username";
$$name="Peter";
print "Welcome ".$username;
?>
Output from the Web Browser
Output from the Web Browser

Constants
PHP constants are variables that have a single value through out their lifetime in the program.
The naming rules for PHP variables applies to constants also except that they dont have a
leading $ (dollar) sign. By convention constants are declared in uppercase. Constants have
global scope, so they are accessible anywhere in the PHP scripts, even inside functions
Although we can define cas e insensitive constants, it is recommended to use case sensitive
constants for it will be consistent and clear when used in the code
A Constant can be declared using the following syntax
define("CONSTANT_NAM E", value [, case_insensitive])
where

"CONSTANT_NAME" is a string.

value is any valid PHP expression excluding arrays and objects.

case_insensitive is a Boolean value (true/false) and is optional. The default value is


false

$purchase_amount=1000;
define ("DISCOUNT_PE RCE NT",20);

$discount_amount=$purchase_amount* DISCOUNT_PERCENT/100;
echo $discount_amount;
An example for a built-in constant is the Boolean value true, which is defined as caseinsensitive.

Managing Variables
The following language constructs helps us to

Check if variable exist

Remove variable

Check variables Truth values

isset() returns a Boolean value depending on the variables existence in a PHP


<?php
$message="hello";
if(isset($message))
print 'Variable $message exist';
else
print 'Variable $message does not exist';
echo "<br>";
if(isset($message1))
print 'Variable $message1 exist';
else
print 'Variable $message1 does not exist';
?>

unset() undeclares an already set variable, and frees any memory that was used by it. Calling
isset() on a variable that has been unset() returns false.

unset($message);
if(isset($message))
print 'Variable $message exist';
else
print 'Variable $message does not exist';
empty() is used to check if a variable has not been declared or its value is false. Generally it
is used to check if a form variable does not contain any data or it has not been sent. The
variables value will be converted to Boolean according to the rules and then it will be
checked for truth-value. The rules for Boolean Conversion will be discussed in the Data Type
section
if (empty($message))
{ print 'Sorry!! No message given';
}
The empty() method evaluates to true if $message does not contain a value that evaluates to
true.

Data Types
PHP supports 8 different data types
Integers
Integers are whole number without a decimal point
int $discount=3000
Read Formats: Integers can be read in three formats

decimal (base 10)

octal (base 8)

hexadecimal (base 16).

Decimal format is the default reading format. Octal integers are specified with a leading 0
and hexadecimals have a leading 0x.
Note that the read format affects only how the integer is converted as it is read the value
stored in $integer_8 does not remember that it was originally written in base 8.
Range of Integer Data type
PHP integers correspond to the C long type, which in turn depends on the word-size of the
machine. For most common platforms, however, the largest integer is 2 1 (or
2,147,483,647) and the smallest integer is (231 1) (or 2,147,483,647)
<?php $integer_10 =-1000;
$integer_8 = 01000;

$integer_16 = 0x1000;
print "integer in decimal format (base 10): $integer_10<BR>";
print "integer in octal format (base 8): $integer_8<BR>";
print "integer in hexadecimal format (base 16): $integer_16<BR>";
?>
Output in the Web Browser

Double
Double values are floating-point numbers
$interest_rate=2.5;
$salary=170000.75;
$temp=52.6E2;
Range of Double
Range of Double is equivalent to C compilers double data type.On common platforms it has
a range of approximately 2.2E308 to 1.8E+308
Boolean
Booleans have only two possible values: TRUE and FALSE.
$status=true;
Boolean constants
PHP also provides Boolean constants TRUE and FALSE
if (true)
print("print when condition is true <br>");
else
print("print when condition is false<br>");
Boolean Rules
The following are the rules by which the truth of a non-boolean value is determined

For Numbers ,all values other than zero evaluate to true and zero evaluates to false

Empty String(has zero characters) and String with the value 0 are evaluated to
false, All other Strings are evaluated to true

NULL values evaluate to false

For compound types like array or an object ,empty array and object(no values)
evaluate t o false

Array and Objects with values evaluate to true. An object contains value, if any one of
its member variable is assigned a value

Valid resources are true (although some functions that return resources when they are
successful, will return FALSE when unsuccessful).

Boolean Rules Summary

$received=0;
if($received)
print "Product shipped successfully";
else
print "Shipment is pending";
will produce the output: Shipment is pending
NULL
The type NULL takes only one possible value called NULL.NULL indicates an unassigned
value, unknown value, no value or lack of value. NULL is a PHP constant and is case
insensitive.
The following assignment statements conveys the same meaning to PHP interpreter, that the
des ignation is not assigned yet
$designation=null;
$designation=NULL;
A Variable when assigned NULL

evaluates to FALSE in a Boolean context.

returns FALSE when tested with IsSet().

PHP will not give any warnings when a NULL value is passed or returned from a
function. But it might sometimes give warnings for a variable that has never been
set ,if passed or returned from a function

String
Strings are sequences of characters.
$message=Knowledge is Power!!!
Strings can be enclosed in either single or double quotation marks with a different
interpretation during read time. Singly quoted strings are treated almost literally, whereas
doubly quoted strings replace variables with their values and treat certain specially
interpreted character sequences in a different way.
Single Quoted and Double Quoted Strings
Single Quoted Strings read and store their values literally apart from treating few specially
interpreted character sequences in a different way
$message='A Clever person solves a problem. A Wise person avoids it';
print 'Albert Einstein says, $message';
The output for the above code will be
Albert Einstein says, $message
We can use a double quote within a single quote.
print 'Albert Einstein says, "A Clever person solves a problem. A Wise person avoids it"';
The output for the above code will be
Albert Einstein says, "A Clever person solves a problem. A Wise person avoids it"
To use a single quote in a single quoted string, escape it with the backslash. To escape a back
slash we can use
\\
$msg=' \' can be used with in \'\' by escaping it using \\';
print $msg;
The output for the above code will be
' can be used with in '' by escaping it using \
Here-Docs

Helps us to include large pieces of text in our scripts, which may include lots of double
quotes and single quotes, without having to escape them.
print <<
Shakespearean quotations such as "To be, or not to be" , "O Romeo, Romeo! wherefore art
thou Romeo?" and "But, for my own part, it was Greek to me" form some of literature's most
celebrated lines. Many expressions that we use every day is from William Shakespeare's
plays. But we are unaware that we are 'borrowing' sayings from his work!
string_here;
The output for the above code will be
Shakespearean quotations such as "To be, or not to be" , "O Romeo, Romeo! wherefore art
thou Romeo?" and "But, for my own part, it was Greek to me" form some of literature's most
celebrated lines. Many expressions that we use every day is from William Shakespeare's
plays. But we are unaware that we are 'borrowing' sayings from his work!
Ensure that the String starts with <<<, followed by a string(Example: string_here) that does
not appear in our text. It is terminated by writing that string (Example: string_here) at the
beginning of a line, followed by an optional semicolon (;), and then a required newline (\n).
Escaping and variable substitution in here-docs is identical to double-quoted strings except
that we are not required to escape them
Accessing Characters in String
Individual Characters within a string can be accessed using $str(offset) format. We can use
this notation to write and read a String. To Write String Characters:
$msg="H";
$msg{1}="e";
$msg{2}="l";
$msg{3}="l";
$msg{4}="o";
echo $msg;
will produce the output
Hello
For reading a character in String, we should use only valid offset/index. String index starts
with 0
$wish="Happy Birthday!";

Output Function

Echo and Print are the 2 the output statements available in PHP.They can be used with or
without parenthesis. The following statements prints the output on the web browser
echo "hello"; // will produce the output : hello
echo ("hello"); // will produce the output: hello
Echo
We can have Multiple Arguments for the echo, when used without parenthesis
echo "Everything is okay in the end, if it's not ok, then it's not the end.","
","Never Give UP!!!";
However, echo when used with parenthesis, can accept only one argument. The above
statement produces an error when used with parenthesis
echo ("Everything is okay in the end, if it's not ok, then it's not the end.","
","Never Give UP!!!");
Print
The print statement is very similar to echo, with two important differences:

Unlike echo, print can accept only one argument.

Unlike echo, print returns a value, which represents whether the print statement was
successful or not.
The value returned by print will be 1 if the printing was successful and 0 if
unsuccessful.
Print 24.5; Print 'c';

Resources
Are special data type, represent a PHP extension resource such as a database query, an open
file, a database connection, and lots of other external types.
Array
An array is a collection of key/value pairs. An array maps keys (or indexes) to values. An
array index can either be an integer or string whereas the value of an array can be of any type
(including other arrays).
$fruits=array("apple","mango","grapes");
echo $fruits[0];
will display apple
Object
Objects are instances of programmer-defi ned classes, which can package both values and
functions that are specific to the class

<?php class Employee


{
var $id=0;
var $name=null;
}
$empobj=new Employee();
$empobj->id=1;
$empobj->name="Sam";
echo "Employee id:".$empobj->id;
echo <br>;
echo "Employee Name:".$empobj->name;
?>
Will produce an output on the web browser as
Employee id: 1
Employee Name: Sam

Operators
Once you know of the existence of variables and constants, you can begin to operate with
them. For that purpose, PHP integrates operators. We use numerous expressions to calculate
some specific value. These expressions make use of many operators. The variables used in
these expressions are operands. Some operators need only one operand and they are called
unary operators. Operators that require two operands are called binary operators and
operators that require three operands are called ternary operators.
Various type of operators supported by PHP are:

Arithmetic Operators

Bitwise Operators

Comparison Operators

Logical Operators

Incrementing/Decrementing Operator

Concatenation Operator

Arithmetic Operators
Arithmetic operators are used to indicat e arithmetic operations such as addition, subtraction,
multiplication, division and modulo.

<?php
$no1=10;
$no2=3;
echo $no1+no2; echo $no1-no2; echo $no1%no2;
?>
Operations of addition, subtraction, multiplication and division literally correspond with their
respecti ve mathematical operators. The only one that you might not have come across is
modulo; Modulo is the operation that gives the remainder of a division of two values. In the
above code snippet the output of $no1%no2 is 1.

Bitwise Operators
A bitwise operator operates on each bit of data. These operators are used for testing,
complementing or shifting bits to the right or left.

Comparison Operators
Comparison operators enable you to determine the relationship between two operands. We
often compare two similar quantities and depending on their relation, take some decisions.
These comparisons can be done with the help of comparison operators. Each of these
operators compare their l eft hand side with their right hand side and evaluate to 0 if the
condition is false and 1 if it is true.

Lets take two numbers 40 and 60, and find out what happens when we use different
comparison operators on them.

40<60 results in true

40>60 results in false

40<=60 results in true

40>=60 results in false

40==60 results in false

40!=60 results in true

40=='40' results in true ---> Automatic type conversion

Note: Automatic type conversion takes place for all the above comparison operators . For the
following two operators, automatic type conversions are not performed.

For example, the operation 40 === '40' results in false.

Comparison Operators
Comparison operators enable you to determine the relationship between two operands. We
often compare two similar quantities and depending on their relation, take some decisions.
These comparisons can be done with the help of comparison operators. Each of these
operators compare their l eft hand side with their right hand side and evaluate to 0 if the
condition is false and 1 if it is true.

Lets take two numbers 40 and 60, and find out what happens when we use different
comparison operators on them.

40<60 results in true

40>60 results in false

40<=60 results in true

40>=60 results in false

40==60 results in false

40!=60 results in true

40=='40' results in true ---> Automatic type conversion

Note: Automatic type conversion takes place for all the above comparison operators . For the
following two operators, automatic type conversions are not performed.

For example, the operation 40 === '40' results in false.

Logical Operators
Logical operators are used in combination with comparison operators to determine if a
condition is true or false. The standard logical operations (AND, OR, and EXCLUSIVE-OR)
are supported by PHP.

The AND operator performs logical conjunction on two Boolean expressions. If both
expressions evaluate to True, then the AND operator returns True. If any one of the
expression evaluate to False, the AND returns False. The OR operator performs logical
disjunction on two Boolean expressions. If either expression evaluates to True, OR returns
True. If neither expression evaluates to True, OR returns False.
XOR performs logical exclusion on two expressions. If either expression evaluates to True,
XOR returns True. If both expressions evaluate to True or both expressions evaluate to False,
XOR returns False.
Note: In AND if the first expression evaluates to false, it wont continue to evaluate the
second expression.

Concatenation Operator
Concatenation operators join multiple strings into a single string. The Dot operator is used for
Concatenation in PHP.
$empname=John;
$empid=1003;
echo Your Employee id is.$empid.<br>;
echo Your name.$empname,<br>;
// The above two lines can be given like this also
echo Your Employee id is.$empid.
Your name.$empname;
The integer $empid is internally converted to the string "1003" before it is concatenated with
the strings prefix,

"Your Employee is".

Increment and Decrement Operator

PHP supports C-style pre- and post-increment and decrement operators. This operator can be
used only with variables and not directly on any value

Note: The increment/decrement operators do not affect Boolean values.


Example :2.1
<?php
echo " <h3>Preincrement</h3> ";
$a = 10;
echo "Should be 10: " . $a++ . "<br />";
echo "Should be 11: " . $a . "<br />";
echo " <h3>Preincrement</h3> ";
$a = 10;
echo "Should be 11: " . ++$a . "<br />";
echo "Should be 11: " . $a . "<br />";
?>
The output of the above code:

Ternary Operator

The ternary operator "?:" earns its name because it's the only operator to take three operands.
It is a conditional operator that provides a shorter syntax for the if..then..else statement. The
first operand is a Boolean expression; if the expression is true then the value of the second
operand is returned otherwise the value of the third operand is returned. The general syntax of
this operator is:
expression?operand1:operand2

For example, the following code snippet checks whether $no1 is greater th an $no2 and
displays a result accordingly
$no1=10;
$no2=20;
$result=($no1>$no2)?"no1 is greater":"no2 is greater";
echo $result;
For the above code the output is displayed as no2 is greater.
tring Manipulation

A string is a series of characters, where a character is the same as a byte. A string literal can
be specified as:
null
$name=tom;
$companyname=ibm;
When writing string values in the source code, we can use double quotes (") and single quotes
(').
For example echo Personal details and echo 'Personal details' will yield the same output,
except in the following case;
$name=tom;
echo your name is $name;
echo 'your name is $name';
The output of the above code is your name is tom your name is $name
When double quotes is used the references to variables are automatically replaced with the
variables values, but in single quotes only the message is printed.

The various methods used to manipulate strings in PHP are:


strtoupper() Converts a string to uppercase.
Strtolower() Converts a string to lowercase.
ucfirst() Converts the first character of a string to uppercase.
ucwords() Converts the first character of each word in a string to uppercase.
strcmp() Compares two strings. Returns < 0 if str1 is less than str2, > 0 if str1 is greater than
str2, and 0 if they are equal.
strlen() Returns the length of a string.
substr(str,po s) Returns the substring from the character in position pos to the end of the
string.
trim() Removes whitespace at the beginning and end of a string.

Example :2.2

<?php
$message="PHP is a server side programming language";
echo " <h3>strtoupper</h3> ";
echo strtoupper($message);
echo " <h3>strtolower</h3> ";
echo strtolower($message);
echo " <h3>ucfirst</h3> ";
echo ucfirst($message);
echo " <h3>ucwords</h3> ";
echo ucwords($message);
echo " <h3>strlen</h3> ";
echo strlen($message);
echo " <h3>substr</h3> ";
echo substr($message,4);
?>

The output of the above code:

Control Structures
So far we have written programs that follow a sequential structure, executing one statement
after another. Using control structures we can execute a statement based on some conditions.
This helps a programmer to control the flow of program execution. In PHP the control
structures are divided into two groups:

Conditional control structures

Loop control structures.

Conditional Control Structures

The conditional control structures affect the flow of the program and execute or skip
certain code according to
certain criteria .PHP supports both the if and switch conditional control structures.

If Statement

The if construct is used when we need to decide which of the available paths is to be taken
based on a certain condition. If the condition that is checked is true, then the statements inside
the if block will get executed.
The syntax of if:
If (expression)
statements;
Example
$age=23;
if(age>=18)
{
echo You are eligible to vote;
}
In the above example the braces are optional. If you have multiple statements inside the if
block then braces are mandatory .You can also use another syntax like the one below:
$age=23;
if(age>=18):
echo You are eligible to vote;
endif;

f-else Statement
The if-else statement provides a secondary path of execution when an "if" clause evaluates to
false. The syntax of the if-else:
if(expression)
statement;
else

statement;
Example
$age=23;
if(age>=18)
echo You are eligible to vote;
else
echo You are not eligible to vote;
If the expression evaluates to true, statements under IF are executed. If false, and there is an
else clause, statements in the else block are executed. If expression evaluates to false, and
there is no else block, execution simply proceeds with the next statement after the if
construct.

If-else if statement
By using Else If, it is possible to combine several conditions. Only the statements following
the first condition that is found to be true will be executed. All other statements are skipped.
The statements of the final Else will be executed if none of the conditions are true.
The syntax of the if-else if:
if(expression)
statement;
else if(expression)
statement;
else if(expression)
statement;
..
else

statement;
Example
$avg=50;
if($avg>=81 and $avg<=90)
{
$grade='O';
echo "Your grade is $grade";
}
else if($avg>=71 and $avg<=80)
{
$grade='A';
echo "Your grade is $grade";
}
else if($avg>=61 and $avg<=70)
{
$grade='B';
echo "Your grade is $grade";
}
else
{
$grade='C';
echo "Your grade is $grade";
}

Nested If

Nested If statements are if statements inside another if statement. The syntax of the nested if
is as follows:
if(expression)
{
if(expression)
statement;
else
statement;
}
else
{
statement;
}
Example
$number=90;
$value=50;
if($number!=0)
{
if($number>0)
{
$result=$value/$number;
echo "result".$result;
}
else
{
echo "give a positive number";

}
}
else
{
echo "You cannot divide a number by zero";
}

Switch Statement
Switch / case is very similar or an alternative to the if / elseif / else commands. The switch
command tests a condition. The outcome of that test dec ides which case to execute. Switch is
normally used when you are finding an exact (equal) result instead of a greater or less than
result.
The syntax of switch:
switch (expression)
{
case value:
statements;
break;
case value:
statements;
break;
... default:
statements;
break;
}

The switch condition is examined and a value is found. The condition value is passed through
the cases. If the value matches a case value, the code in that block is executed. If the valu e
does not match any of the case values, the default section is executed. Once a block of coding
is finished, the BREAK command is used to jump out of the switch/case area.
Example
Let's imagine you own a computer retail store. Depending on the product nam e we need to
display the price of that product. Now, instead of writing separate if else statements for each
product name, we simply use the switch statement on the product name variable to evaluate
which product we want to the display the price for.
For example:
$product_name = "Processors";
switch ($product_name)
{
case "Video Cards":
echo "Video cards range from $50 to $500";
break;
case "Monitors":
echo "LCD monitors range from $200 to $400";
break;
case "Processors":
echo "processors range from $100 to $1000";
break;
default:
echo "Sorry, we don't carry $product_name in our catalog";
break;
}
if someone asks for a product and if it is not available in the store, in that case, the statements
in the default block get executed.
Example

$choice='y';
switch($choice)
{
case 'y':
echo Your choice is yes;
break;
case 'n':
echo Your choice is no; break;
default:
echo no correct match;
}
In the above example the user can opt for either y or n. In case the user types Y or N,
the statements in the default block will be executed. We solve this in the following manner:
$choice='y';
switch($choice)
{
case 'y':
case 'Y:
echo Your choice is yes;
break; case 'n': case 'N':
echo Your choice is no;
break;
default:
echo no correct match;
}

Loop Control Structures


Loop control structures execute certain code arbitrary number of times according to specified
criteria. They are used for repeating certain tasks in the program, such as iterating over a
database query result set.
PHP supports for, while, do-while and for each.

For Loop
The for loop is used to perform a set of operations repeatedly until some condition is
satisfied. The syntax of a for loop is;
for(initialization:test-condition:increment/decrement)
statement; (or)
for(initialization:test-condition:increment/decrement):
statement;
endfor;
The initialization is evaluated just once, usually to initialize variables. Then the test-condition
is evaluated if false, the loop exits, and if true, the statements inside the for loop is
executed. Finally, the increment/decrement expression is executed and the cycle begins again
with the test-condition.

Example

for ($i = 0; $i < 10; $i++)


echo "The square of $i is " . $i*$i . "\n";

While Loop
The function of the while loop is to do a task over and over as long as the specified
conditional statement is true. The syntax of while loop is:
while(testcondition)
statement; (or)
while(testcondition):
statement;
endwhile;
Example

$counter=8;
while($counter<10):
echo The counter value.$counter;
endwhile;

Do-while loop

he functionality of do-while is exactly the same as the while loop, except that the condition in
the do- while loop is evaluated after the execution of statement and not before. This means
that the loop always runs at least once. The syntax of the do-while loop is:
do
{
statements;
}while(testcondition);

Example
$choice='y';
do
{
echo "1.Display the student details";
echo "2.Add the student details";
echo "Do you want to continue";
}while($choice=='n');

The do-while is mainly used for menu-based applications.

Note:
The for each loop provides an easy way to iterate over arrays (see unit-4)

Loop Control: break and continue

Sometimes, we will have to terminate the execution of a loop in the middle of an iteration.
For this purpose, PHP provides the break statement.
Example: Program to extract only the name from the emailid.
.

$emailid="john@ibm.com";
$length=strlen($emailid);
for($i=0;$i<$length;$i++)
{
if($emailid[$i]=='@')
{

break;
}
else
{
echo $emailid[$i];
}
}
In the above example, once an @ symbol is encountered the control comes out of the loop.
If Break appears alone, the innermost loop is stopped. Break accepts an optional argument of
the amount of nesting levels to break out of, break n; which will break from n innermost
loops (break 1; is identical to break ).
For example:
for($i=0;$i<5;$i++)
{
for($j=0;$j<5;$j++)
{
echo $i." ".$j."<br>";
if($j==3)
break 2;
}
}
In this example, once the if condition evaluates to true the control comes out of the outer
loop. Instead of break

2, if you have said just break , it will exit only from the inner loop. The output of the above
program will be 0 0, 0
1, 0 2, 0 3.

Continue
Continue is used within looping structures to skip the rest of the current loop iteration and
continue execution at the condition evaluation and then the beginning of the next iteration.
Continue also accepts an optional numeric argument which mentions how many levels of
enclosing loops it should skip to the end.
Example: A program to print only odd number from 1to 10

for($i=0;$i<10;$i++)
{
if($i%2==0)
{continue;
}
echo $i."<br>";
}
In this example if the if statement evaluates to true, it will not execute the remaining
statements in the loop.

CLASS AND OBJECTS

Introduction
Support for Object Oriented Language was introduced from PHP 3. There was no major
improvement in the features of PHP 4 as backward compatibility was the main concern.
When demand for the OOP approach increased, many new features were introduced and
added in PHP 5

Object

An Object is a real world entity of the problem domain under concern, which is described
through certain property and has a definite role to play in the system. Object Oriented
Applications have several such objects that interact with each other to perform a business
operation.
For example, An Online Shopping Cart application would have Customer and Product objects
where Customer "purchases" a Product online.

Class
A class is a template that describes attributes and methods of a certain object type.
For example, the Customer class defines the attributes and behaviors that all Customers have
and perform in an Online Shopping Cart.

Defining Class in PHP


Class in PHP is created using the following Syntax.
class Classname
{
//Define Properties
//Define Methods
}
The Customer class in PHP is defined as follows
class Customer
{
private $name;
private $age;
}
function setName($name)
{
$this->name=$name;

}
function setAge($age)
{
$this->age=$age;
}
function getName()
{
return $this->name;
}
function getAge()
{
return $this->age;
}
}

Object in PHP

Object is a runtime instance of a class.


From class Customer, we can create many Customer Objects. Every Object is an instance of
Customer

Creating an Object

An Object is created using the "new" keyword. The following code creates a
Customer object
$custobj=new Customer();
To assign the values for object property, the setter method is called.
$custobj->setName("Joe");
$custobj->setAge(25);
To access the property values, the getter method is called.
print "Customer Name:".$custobj->getName();
print "<br>";
print "Customer Age:".$custobj->getAge();

The output of the above code is


Customer Name: Joe
Customer Age:25
Private property cannot be accessed directly outside the class. To retrieve and modify its
values we need to use the getter and setter methods. The keyword "private" is used before the
property variable to declare it as private. Alternatively a property can also be declared public.
Public property, as the name indicates can be accessed outside the class .The keyword
"public" is used before the property variable to declare it as public .
If customer name had been declared "public" then the values of it can be set and retrieved as
follows ;
class Customer
{
public $name;
public $age;
//other code
}
$custobj=new Customer();
$custobj->name="Joe";
print $custobj->name;

sage of $this variable


The $this variable is automatically defined during the execution of the object's method. It is
used to refer the properties of an Object.

Constructor
Constructors are used to initialize the state of the object during object creation.

Constructor is a function defined using "__construct" keyword

Constructor is automatically called during object creation, using the "new" keyword

Constructor can accept parameters

class Customer

{
private $name;
private $age;
function __construct()
{
$this->name="Joe";
$this->age=25;
}
function setName($name)
{
$this->name=$name;
}
function setAge($age)
{
$this->age=$age;
}
function getName()
{
return $this->name;
}
function getAge()
{
return $this->age;
}
}

The Customer object is created as usual, but this time the constructor is called and the name
and age of the customer is initialized as defined in the constructor.
$custobj=new Customer();
Getter methods are used to retrieve customer details.
print "Customer Name:".$custobj->getName();
print "<br>";
print "Customer Age:".$custobj->getAge();
The output of the above code will be
Customer Name: Joe
Customer Age: 25

Constructor with Parameters


Using the Constructor defined above, all customers will be Joe with age 25. Incidentally few
customers can have the same name and age, but practically not all customers can have the
same name and age.
To create a Customer object with meaningful details, a parameterized constructor is used.
Instead of creating a constructor with hard coded values, a constructor that can accept
parameters is used.
We can rewrite the constructor defined above as follows;
function __construct($name,$age)
{
$this->name=$name;
$this->age=$age;
}
Customer objects are created using the parameterized constructor
$custobj1=new Customer("Philip",45);
$custobj2=new Customer("Joe",25);
The following code snippet prints the customer details
print "Customer Name:".$custobj1->getName();
print "<br>";
print "Customer Age:".$custobj1->getAge();
print "<br>";
print "Customer Name:".$custobj2->getName();
print "&ly;br>";
print "Customer Age:".$custobj2->getAge();
The output of the above code will be

Customer Name:Philip
Customer Age:45
Customer Name:Joe
Customer Age:25

Introduction
PHP is generally used for developing web based applications, and forms are the key part for
most web applications, primarily for capturing user inputs. This unit introduces how to define
forms in html and manipulate the data captured through the forms, using PHP.

Creating Forms in HTML


Forms are used to gather information from the user, and depending on your needs, you may
store that information into a file or database, place an order, gather user statistics, register the
person to your web forum etc. Let us see an example where we create a registration form
named registrationform.html.
<html>
<body>
<h1><center>Resistration Form></h1>
<form action="Registrationdetails.php" method="post">
<table align="center">
<tr><td>Name</td><td><input type="text" name="uname"></td></tr>
<tr><td>Age</td><td><input type="text" name="age"></td></tr>
<tr><td>Select Qualification</td><td><select name="qualification"
name="uname"></td></tr>
<option value=none>None</option>
<option value="BE">BE</option>
<option value="ME">ME</option>
</select></td></tr>
<tr><td>Gender</td><td>Male<input type="radio" name="gender"
value="male"></td>
<td>Female<input type="radio" name="gender" value="female"></td></tr>
<tr><td>Hobbies</td>
<td>Sport<input type="checkbox" name="hobbies[]" value="sport"> </td>
<td>Music<input type="checkbox" name="hobbies[]" value="music"> </td>
<td>Painting<input type="checkbox" name="hobbies[]" value="painting"> </td>
</tr>
<tr><td><input type="submit" value="Register"></td><td>

<input type="reset" value="Clear"></td></tr>


<table>
</form>
</body>
</html>
The name of the hobbies field is slightly different from other fields. Since we are going to
retrieve multiple values, we need to treat the hobbies itself as an array.

The above form holds various components like textboxes, radio buttons, checkboxes, buttons
etc. When a user fills out the above form and click on the register button, the form data is sent
to a PHP file, called "Registrationdetails.php". In the form attribute we have given the
method name as post. The method tells the browser how to send the data. Here we can use
either the POST or GET method.
Note: The names of the components are case sensitive

GET and POST


In the GET method, the form submission values are passed as part of the URL. In case of the
POST method, the information is sent to the server as part of the data body and is not visible
in the URL box in the users browser. When we dont specify the method, GET is taken by
default. In the above example if we had used the GET method and submitted the form, the
URL would look like:

http://localhost/SampleApp/Registrationdetails.php?
uname=John&age=24&qualification=BE&gender=male&hobbies%5B%5D=sport&hobbies
%5B %5D=music

In the URL name, value pairs are joined with equal signs and different pairs are separated by
the ampersand. In case of POST the URL would look like:
http://localhost/SampleApp/Registrationdetails.php

As mentioned earlier, while using POST the data is not visible in the URL.
The GET method is restricted to send up to 1024 characters only whereas the POST method
does not have any restriction on data size to be sent. Never use GET method if you have
password or other sensitive information to be sent to the server.

Accessing form data


When a form is submitted to a PHP script, the information from that form is automatically
made available to the PHP script.

$_POST
In the above example the form data is submitted to the "Registrationdetails.php" script using
the POST method. PHP will store all the "posted" values into an associative array called
"$_POST". The name of each component in form will be a key in the $_POST associative
array as:
$yourhobbies= array("sports", "music");
$_POST array("uname"=>"John", "age"=>"24","gender"=>"male","qualification"=>"BE",
"hobbies"=>$yourhobbies);
To access the data in Registrationdetails.php we need to say:
$name=$_POST[uname];
echo $name;
uname is the name of the textbox. According to our example John would get printed.
In our example we have hobbies as a checkbox, the user can choose more than one option, in
that case we need to retrieve as:
$myhobbies=$_POST["hobbies"];
$myhobbies is treated as an array which will hold more than one value; we need to use some
looping construct to retrieve the values.

$noofhobbies=count($myhobbies);
for($i=0;$i<$noofhobbies;$i++)
{
echo "<br>".$myhobbies[$i];
}
Code in Registrationdetails.php:
<?php>
$name=$_POST["uname"];
$age=$_POST["age"];
$gender=$_POST["gender"];
$myhobbies=$_POST["hobbies"];
$qualification=$_POST["qualification"];
echo"<h3>";
echo "Name
:".$name."<br>";
echo "Age
:".$age"<br>";
echo "Gender
:".$gender."<br>";
echo "Qualification :".$qualification."<br>";
echo "Hobbies :";
$noofhobbies=count($myhobbies);
for($i=0;$i<$noofhobbies;$i++)
{
echo $myhobbies[$i].",";
}
echo "</h3>";
?>
After filling the form once when we click the register button we get the output as:

In our registrationform.html we have given the checkbox as:


<input type="checkbox" name="hobbies[]" value="sport">
As discussed earlier the hobbies is like an array here. There are some situations where we
need to use checkboxes for storing a single value instead of multiple values. Let us include
one more component in registrationform.html page as:
<input type="checkbox" name="terms" value="y">I accept the terms and
condition>
Now our form will look like:

To retrieve the value in the PHP page we need to say:


$status=$_POST[terms];
The $status holds the value y. Based on $status, for example to check if the user has not
accepted the terms and condition the message Sorry we can't process your form is
displayed. For example we can modify the Registrationdetails.php page as:
<?php
error_reporting(E_USER_ERROR);
$status=$_POST["terms"];
if($status=="y")
{
$name=$_POST["uname"];

$age=$_POST["age"];
$gender=$_POST["gender"];
$myhobbies=$_POST["hobbies"];
$qualification=$_POST["qualification"];
echo "<h3>";
echo "Name
:".$name."<br>";
echo "Age
:".$age."<br>";
echo "Gender
:".$gender."<br>";
echo "Qualification :".$qualification."<br>";
echo "Hobbies :";
$noofhobbies=count($myhobbies);
for($i=0;$i<$noofhobbies;$i++)
{
echo $myhobbies[$i].",";
}
echo "</h3>
}
else
{
echo "Sorry we can't process your form";
}
?>

$_GET
In our example we have used the POST method to send the data. If we use the GET method
we need to use $_GET to access the data in the PHP page. For example:
$_GET[uname];
$_GET[age];
In the registrationform.html we need to change the method name as:
<form action=Registrationdetails.php>
We have not specified any method name in the above statement and as mentioned earlier by
default it would be GET.

$_REQUEST
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. For example in Registrationdetails.php file we can access the
data as (note: we have used the POST method in the form):
$name=$_REQUEST[uname];

File Upload
As Web designers and application developers, we tend to think of the ability to upload files
via the Web as a really cool and useful feature. Using PHP we can upload a file to the server
To upload a file to the server, we need to provide a form to specify which file they want to
upload. So far we have created a form to send only textual inputs. Let us see an example of
how to design a form to implement file upload.
<html>
<body>
<body>
<h3>
<form action="uploadfile_action.php" method="POST" enctype="multipart/form-data">
Upload this File<input type="file" name="filetoupload">
<input type="submit" value="Upload" \>
</h3>
</form>
</body>
</html>
</body>
</html>
In the <form> tag we need to set the attribute enctype=multipart/form-data to let the server
know that a file is coming along with the regular form information. The <input> tag with the
type file is the file upload field and it creates a file browser button in the web browser. The
method name should be POST. The

output of the above code will be:

Handling the Incoming Uploaded File


Once the user uploads a file, the file is uploaded into a temporary location on the server. This
is the server's default temporary directory. If we do not move the file before our script
finishes execution it will be deleted. Whenever a file is uploaded, we can find out certain
information about the file such as its name, type, size, as well as the name of the temporary
file on the server. These details are made available to you via a PHP array called $_FILES.
$_FILES
The $_FILES array contains an array of information about each file that is uploaded. The
handler script can access the information using the name of the uploaded file as the key. The
$_FILES[''filetoupload] (note:The filetoupload is the name we have given in the HTML
form) variable contains the following information for the uploaded file.

In our example we need to browse and choose the file that needs to be uploaded. After
choosing the file, when we click upload the control we will be moved to
uploadfile_action.php. Let us see an example to retrieve the above mentioned details in the
uploadfile_action.php page:
<?php
$filename=$_FILES['filetoupload']['name'];
$type=$_FILES['filetoupload']['type'];
$tempname=$_FILES['filetoupload']['tmp_name'];
$filesize=$_FILES['filetoupload']['size'];
echo "File Name:".$filename."<br>";
echo "File Type:".$type."<br>";
echo "Temporary Name:".$tempname."<br>";
echo "File Size:".$filesize.."<br>"; ?>
The output of the above code will be:

Note: The $_FILES array gets populated only for POST method.

Saving the Uploaded File


As mentioned earlier the uploaded file will be stored in the server's temporary location. If we
do not move the file before our script finishes execution it will be deleted. So we need to save

the uploaded file permanently in some location. The following code demonstrates how to
move the file from the temporary location:
move_uploaded_file($_FILES["filetoupload"]["tmp_name"],
"C:/upload/" . $_FILES["filetoupload"]["name"]);
move_uploaded_file() function moves an uploaded file to a new location. While invoking this
function we need to pass the temporary file location and the new location where the file is to
be moved.

Restricting File Type/Size


Letting your users upload files to your server can be very risky. If you are not careful, you
could get users uploading all sorts of files. You could also find one day that you have run out
of disk space because some users have been uploading files of enormous sizes. In the script
you can add some restrictions to the file upload. For example the user should upload only .txt
files and the file size should be less than 100 bytes.
Example:
if($_FILES['filetoupload']['type']=="text/plain")
{
if($_FILES['filetoupload']['size']<100)
{
$templocation=$_FILES['filetoupload']['tmp_name'];
$newlocation="C:/wamp/www/SampleApp/".$_FILES['filetoupload']['name'];
move_uploaded_file($templocation, $newlocation);
}
else
{
echo "Files size should be less than 100 bytes";
}
else
{
echo "Upload .txt file";
}

Checking for Errors


The $_FILES array includes an item for any errors that may result from the upload. This
contains an error code. If there are no errors, the value is zero (0). To handle this situation
where the user clicks the upload button without choosing the file that needs to uploaded, the
following code can be used:
if($_FILES['filetoupload']['error']==4)
{

echo "Please choose the file";


}
else
{
$templocation=$_FILES['filetoupload']['tmp_name'];
$newlocation="C:/wamp/www/SampleApp/".$_FILES['filetoupload']['name'];
move_uploaded_file($templocation, $newlocation);
}
Most of the errors relate to the size of the uploaded file. Each error code has an associated
constant. The following table shows the error conditions:

What is a Database?
A database is a collection of organized information that can be accessed, managed and
manipulated efficiently.

Relational Database
Relational Database is one of the approaches to store and manage data. A Relational Database
stores data in a tabular format.
For Example, Student details are maintained in the following format. Every column is
identified as a field and every row is identified as one Student record.

MYSQL Data types


MYSQL fields are associated with a data type during their creation, representing the value
they can store.
The following are few data types supported by MYSQL;

SQL
SQL is an ANSI (American National Standards Institute) standard language for querying and
manipulating relational databases.
Purpose of SQL
The following are few tasks that can be performed using SQL
Create Database

Create tables and managing the table structure


Add, update and delete information from database
Retrieve information from database

CREATE TABLE command


The Create Table Command is used to create a table in MYSQL database
Syntax
Create Table table_name(
Column_list
)
The following command creates a product table with product id, product name and price.
create table product(product_id int, product_name varchar(50),price decimal);

DESCRIBE Command
To view the tables metadata information, we use the DESCRIBE command.
Syntax
DESC[RIBE] table_name

To following displays the metadata information about the product table.


Describe product;

Constraints

Constraints are used to place restrictions on the table data


Constraints can be specified during table creation (CREATE TABLE command ) or after
creating the table(ALTER command).
Constraints that can be placed on the table are
Not Null
Unique
Primary Key
Foreign Key Check
NOT NULL
A NOT NULL constraint is used to enforce that a column should always contain a value. A
NOT NULL column cannot contain a NULL value.
UNIQUE
UNIQUE constraint enforces column values to be unique. A UNIQUE column cannot contain
duplicate values.
PRIMARY KEY
PRIMARY KEY constraint is used to identify a record uniquely within a table. A column
declared as PRIMARY KEY is by default UNIQUE and NOT NULL.
A table can have many unique columns, but can contain only one primary key.
The primary key identified in the table can be made up of one or more columns.
The following command creates the product table with product_id as primary key and other
columns as not null
Create table product(product_id int primary key,product_name varchar(50) not null,price
decimal not null);
FOREIGN KEY
A FOREIGN KEY in one table refers to a PRIMARY KEY in another table.
A column that is declared as a Foreign KEY can have only those values of the PRIMARY
KEY column it refers to or NULL. It cannot have any other values.
Assume the Product table has the following information;

The Order table contains the orderid ,products ordered and quantity.

Product_id is the primary key in the Product table. The product id in the ORDER table refers
to the product id in the PRODUCT table. Therefore product_id in ORDER table has to be
declared as a foreign key.
Create table product_order(order_id int primary key,product_id int references
product(product_id), price float not null);
CHECK
Check constraint for a column enforces the values of that column satisfies the check
constraint
Assume that the product table has a column called as product_category. The product category
can have values that can be either Stationary or Electronics or Kitchen Ware. This is
enforced using CHECK constraint as follows.
Create table product(product_id int primary key,product_name varchar(50) not null,price
decimal not null,product_category check product_category in(Stationary, Kitchen Ware,
Electronics))

List down tables in the database


The SHOW TABLE command displays all table names available in the current database
Syntax

SHOW TABLES

Alter Command
Alter command is used to modify the existing table structure.
Add a new column:
Syntax
Alter table table_name add [column definition]
To add a new column to the product table,
Alter table product add description varchar(50);

Modify existing column:


Syntax
Alter table table_name modify [column definition]
To modify the data type of the price from decimal to float Alter table product modify price float;

Drop Existing Column


Syntax
Alter table table_name drop column_name
To drop the description column in the product table Alter table product drop description;

Drop TABLE Command


The Drop Table command is used to delete an existing table from the database
Syntax
Drop table table_name;
To drop the product table
Drop table product;

select Database
To execute the queries, the database to work with has to be selected. mysql_select_db()
method is used to select a database.

Syntax
mysql_select_db("database_name", $connection);
To work with a database called SampleDB,
mysql_select_db("my_db", $con);

SQL Functions
SQL has many in-built functions.
SQL Aggregate Functions
SQL aggregate functions return a single value, computed from values of a column.
Some of the aggregate functions:
AVG() - Returns the average value
COUNT() - Returns the number of rows
MAX() - Returns the largest value
MIN() - Returns the smallest value
SUM() - Returns the sum
To find the total number of products available in the Product Store we can use COUNT
function
Select count(*) as Products Available from product;
Products Available will be shown as column heading during display

To find maximum price of a product;


Select max(price) as 'MAXIMUM PRICE OF A PRODUCT' from product;

DML Statements
DML Statements are used to manipulate the values within the database tables through insert,
update and delete commands.
INSERT
INSERT Command is used to insert new rows into database tables.
UPDATE
UPDATE command is used to modify the values of existing rows in database tables.
DELETE
DELETE command is used to delete existing rows from database tables.
INSERT Command
Syntax
The basic syntax of INSERT command is;
INSERT into table_name values(value_1,value_2,value_3.value_n)
The following command inserts product information into the product table.
insert into product values(1,'IPOD', 30000.75);

UPDATE Command
The basic syntax of UPDATE command is
Syntax
Update table_name set column_name=value,column_name=value, [where condition]
The following command updates the price of IPOD from 30000 to 32500;
Update product set price=32500 where product_id=1;

DELETE Command
The basic syntax of DELETE command is
Syntax
Delete from table_name [where condition]
The following command deletes the product id 1.
Delete from product where product_id=1;

HP and MYSQL
The following steps are required for PHP to communicate with MYSQL database;
Obtain Database Connection
Select Database
Execute Queries
Close Database Connection

Obtain Database Connection


mysql_connect() is used to obtain connection to MYSQL database.
Syntax
mysql_connect(servername, username, password);

Servername
Server name specifies the database server to connect to. Default value is "localhost:3306"
Username
Username specifies the username to log in to the MYSQL database. Default value is the name
of the user that owns the server process.
Password
Password specifies the password to log in to the MYSQL database. Default password is ""
The following code displays the Database Connection Obtained message if the username
and password is correct and the connection is obtained. The mysql_connect() returns a
boolean value indicating the connectivity status.
<?php
$con = mysql_connect("localhost","john","pwd");

if (!$con)
echo "Sorry!!!! Connection cannot be obtained";
else
echo "database Connection Obtained";
?>

Select Database
To execute the queries, the database to work with has to be selected. mysql_select_db()
method is used to select a database.
Syntax
mysql_select_db("database_name", $connection);
To work with a database called SampleDB,
mysql_select_db("my_db", $con);

Execute Queries
All SQL queries can be executed using the mysql_query() method.
Syntax
mysql_query($query);
Insert a Product Record
The Following query inserts a product into the product table.
$sql="insert into product values(4,'MEMORYCARD-2GB',250)";
$result=mysql_query($sql);
On Successful execution of the query, the mysql_query () method returns an integral value
indicating the number of rows that was affected because of that query.
In the above scenario, the method would have returned a value 1 on successfull execution of
the query.
An appropriate message can be displayed depending on successful query execution.
The following code snippet displays a message depending on the query execution status;
if($result>0)
echo "Product Added Successfully!!! ";
else
echo "Product Not Added!!!";

View Product Details


The following code snippet displays details of all products available in the product table. If
no product exists, it displays the No Product Exists message;
The mysql_num_rows($result) method returns the number of rows returned by the query.
The mysql_fetch_array($result) method returns the current row as an associative array.
$sql="select * from product" ;
$result=mysql_query($sql);
if (mysql_num_rows($result)==0)
{ echo "No Such Product exists";
}
else
{ echo "<table border=1 align=center";>
echo "<tr bgcolor=#F3F3F3><td>Product Id</td><td>Product Name</td><td>Product
Price</td></tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>".$row["product_id"]."</td>";
echo "<td>".$row["product_name"]."</td>";
echo "<td>".$row["price"]."</td></tr>";
}
echo "</table>";
}
The output of the above code will be

Close Database Connection


mysql_close() method is used to close the connection
Syntax
mysql_close($connection);

To close the connection obtained in $con


mysql_close($con);

Vous aimerez peut-être aussi