Server Side Scripting PHP
Server Side Scripting PHP
With PHP
What is PHP?
<?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".
• Note: The file must have a .php extension. If the
file has a .html extension, the PHP code will not
be executed.
Comments in PHP
+ Addition x=2 4
x+2
Subtraction x=2 3
5-x
* Multiplication x=4 20
x*5
/ Division 15/5 3
5/2 2.5
% Modulus (division remainder) 5%2 1
10%8 2
10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--
Assignment Operators
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
.= x.=y x=x.y
%= x%=y x=x%y
Comparison Operators
== is equal to 5==8 returns false
!= is not equal 5!=8 returns true
<> is not equal 5<>8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than or equal to 5>=8 returns false
<= is less than or equal to 5<=8 returns true
Logical Operators
Operator Description Example
&& and x=6
y=3 (x < 10 && y > 1) returns true
|| or x=6
y=3 (x==5 || y==5) returns false
! not x=6
y=3 !(x==y) returns true
PHP If...Else Statements
• Conditional statements 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.
• In PHP we have the following conditional statements:
• if statement - use this statement to execute some code
only if a specified condition is true
• if...else statement - use this statement to execute some
code if a condition is true and another code if the
condition is false
• if...elseif....else statement - use this statement to select
one of several blocks of code to be executed
• switch statement - use this statement to select one of
many blocks of code to be executed
The if Statement
• Use the if statement to execute some code only if a
specified condition is true.
• Syntax
• if (condition) code to be executed if condition is true;The
following example will output "Have a nice weekend!" if
the current day is Friday:
• <html>
<body>
<?php
$d=date("D");
if ($d=="Fri") echo "Have a nice weekend!";
?>
</body>
</html> Notice that there is no ..else.. in this syntax. You
tell the browser to execute some code only if the
specified condition is true.
• The if...else Statement
• Use the if....else statement to execute some
code if a condition is true and another code if a
condition is false.
• Syntax
• if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
• 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!";
else
echo "Have a nice day!";
?>
</body>
</html>
• 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>
• The if...elseif....else Statement
• Use the if....elseif...else statement to select one of several blocks of code to
be executed.
• 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;
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>
PHP Switch Statement
• Conditional statements are used to perform different actions based
on different conditions.
• The PHP Switch Statement
• Use the switch statement to select one of many blocks of code to be
executed.
• Syntax
• switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from both label1 and label2;
}
• This is how it works: First we have a single
expression n (most often a variable), that is
evaluated once. The value of the expression is
then compared with the values for each case in
the structure. If there is a match, the block of
code associated with that case is executed. Use
break to prevent the code from running into the
next case automatically. The default statement is
used if no match is found.
Example
• <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>
PHP Arrays
• An array stores multiple values in one single variable.
• What is an Array?
• A variable is a storage area holding a number or text.
The problem is, a variable will hold only one value.
• An array is a special variable, which can store multiple
values in one single variable.
• If you have a list of items (a list of car names, for
example), storing the cars in single variables could look
like this:
• $cars1="Saab";
$cars2="Volvo";
$cars3="BMW"; However, what if you want to loop
through the cars and find a specific one? And what if you
had not 3 cars, but 300?
• The best solution here is to use an array!
• An array can hold all your variable values under a single name. And
you can access the values by referring to the array name.
• Each element in the array has its own index so that it can be easily
accessed.
• In PHP, there are three kind of arrays:
• Numeric array - An array with a numeric index
• 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 array element with a numeric index.
• There are two methods to create a numeric array.
• 1.
• In the following example the index are
automatically assigned (the index starts at 0):
• $cars=array("Saab","Volvo","BMW","Toyota"); 2.
In the following example we assign the index
manually:
• $cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
• Example
• In the following example you access the variable
values by referring to the array name and index:
• <?php
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
echo $cars[0] . " and " . $cars[1] . " are Swedish
cars.";
?>The code above will output:
• Saab and Volvo are Swedish cars.
• 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"; The ID keys can be used in a script:
• <?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.
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"
)
);
• 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
)
) 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?
• Loops execute a block of code a specified number of times, or while a specified
condition is true.
• PHP Loops
• Often when you write code, you want the same block of code to run over and over
again in a row. Instead of adding several almost equal lines in a script we can use
loops to perform a task like this.
• In PHP, we have the following looping statements:
• while - loops through a block of code while a specified condition is
true
• do...while - loops through a block of code once, and then repeats
the loop as long as a specified 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
• The while Loop
• The while loop executes a block of code while a condition is true.
• Syntax
• while (condition)
{
code to be executed;
}
Example
• The example below defines a loop that starts with i=1.
The loop will continue to run as long as 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> Output:
• The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The do...while Statement
• The do...while statement will always execute the block of
code once, it will then check the condition, and repeat
the loop while the condition is true.
• Syntax
• do
{
code to be executed;
}
while (condition);
• The example below defines a loop that starts with i=1. It
will then increment i with 1, and write some output. Then
the condition is checked, and the loop will continue to
run as long as i is less than, or equal to 5:
Example
• <html>
<body>
<?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i<=5);
?>
</body>
</html> Output:
• The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The foreach Loop
• Syntax
• function functionName()
{
code to be executed;
}
• PHP function guidelines:
• Give the function a name that reflects what the function
does
• The function name can start with a letter or underscore
(not a number)
Example
• A simple function that writes my name when it is called:
• <html>
<body>
<?php
function writeName()
{
echo “my name";
}
echo "My name is ";
writeName();
?>
</body>
</html> Output:
• My name is my name
PHP Functions - Adding parameters
• <form action="welcome.php"
method="get">
Name: <input type="text" name="fname"
/>
Age: <input type="text" name="age" />
<input type="submit" />
</form>
• When the user clicks the "Submit" button, the
URL sent to the server could look something like
this:
• http://www.w3schools.com/welcome.php?fname
=Peter&age=37 The "welcome.php" file can now
use the $_GET function to collect form data (the
names of the form fields will automatically be the
keys in the $_GET array):
• Welcome <?php echo $_GET["fname"]; ?>.<br
/>
You are <?php echo $_GET["age"]; ?> years
old!
When to use method="get"?
mysql_select_db("mydb",$db);
<?php
include("emptyfile.inc");
echo "Hello World";
?>
</body>
</html>
• Information common to all pages can be
placed inside include files
• Things like HTML headers, footers,
database connection code, and user-
defined functions are all good candidates.
• Paste this text into a file called header.inc.
<?php
$db = mysql_connect("localhost", "root");
mysql_select_db("mydb",$db);
?>
<html>
<head>
<title>
<?php
echo $title ?>
</title>
</head>
<body>
<center>
<h2>
<?php
echo $title
?>
</h2>
</center>
Footer
• Then create another file called footer.txt
that contains some appropriate closing
text and tags.
• Now let's create a third file containing the
actual PHP script.
• Try the following code, making sure that
your MySQL server is running.
• The include files are tossed into the main file
and then the whole thing is executed by PHP.
Notice how the variable $title was defined before
header.inc is referenced. Its value is made
available to the code in header.inc; hence, the
title of the page is changed.
• You can now use header.inc across all your
PHP pages, and all you'll have to do is change
the value of $title from page to page.
• Using a combination of includes, HTML,
conditional statements, and loops, you can
create complex variations from page to page
with an absolute minimum of code. Includes
become especially useful when used with
functions.
• The mysql_fetch_array() function.
• This is exactly the same as mysql_fetch_row()
with one nice exception:
• Using this function, we can refer to fields by their
names (such as $myrow["first"]) rather than their
numbers.
• This should save us some headaches. We've
also introduced a do/while loop and an if-else
statement.
• Everything's about the same
except the printf function, so let's
look at it in some detail.
• First notice that each quotation
mark is proceeded by a
backslash.
• The backslash tells PHP to
display the character following it,
rather than treat it as part of the
code.
• Also note the use of the variable
$PHP_SELF.
• This variable, which stores the script's
name and location, is passed along with
every PHP page.
• It's helpful here because we just want this
file to call itself. Using $PHP_SELF, we
can be sure that will happen, even if the
file is moved to another directory - or even
another machine.
<html>
<body>
<?php
$db = mysql_connect("localhost", "root");
mysql_select_db("mydb1",$db);
// display individual record
if ($id)
{
$result = mysql_query("SELECT * FROM
employees WHERE id=$id",$db);
$myrow = mysql_fetch_array($result);
printf("First name: %s\n<br>", $myrow["first"]);
printf("Last name: %s\n<br>", $myrow["last"]);
printf("Address: %s\n<br>", $myrow["address"]);
printf("Position: %s\n<br>", $myrow["position"]);
}
else
{ // show employee list
$result = mysql_query("SELECT * FROM employees",$db);
if ($myrow = mysql_fetch_array($result))
{ // display list if there are records to display
do
{
printf("<a href=\"%s?id=%s\">%s %s</a><br>\n", $PHP_SELF,
$myrow["id"], $myrow["first"], $myrow["last"]);
} while ($myrow = mysql_fetch_array($result));
}
else
{
// no records to display
echo "Sorry, no records were found!";
}
}
?>
</body></html>
Throw in Some Forms
• <html>
• <body>
• <form method="post" action="<?php echo
$PHP_SELF?>">First name:<input type="Text"
name="first"><br>Last name:<input type="Text"
name="last"><br>Address:<input type="Text"
name="address"><br>Position:<input
type="Text" name="position"><br><input
type="Submit" name="submit" value="Enter
information">
• </form>
• </body>
• </html>