What Is PHP
What Is PHP
2
Where to Start?
• Install an Apache server on a Windows or
Linux machine
• Install PHP on a Windows or Linux
machine
• Install MySQL on a Windows or Linux
machine
3
• Download PHP for free here:
http://www.php.net/downloads.php
4
Basic PHP Syntax
• A PHP scripting block always
– starts with <?php and
– ends with ?>
• Example
<?php
…….….
………..
?>
5
What is a PHP File?
• A PHP file normally contains
6
Combining HTML and PHP
<html>
<head>
<title>A PHP script including HTML</title>
</head>
<body>
<b>
"hello world- HTML";
<?php
echo "hello world-PHP";
?>
</b>
</body>
7
</html>
Comments in PHP
• In PHP, we use
8
Example
<html>
<body>
<?php
//This is a single-line comment
/*
This is
a comment
block
*/
?>
</body>
</html>
9
Variables in PHP (temporary
storage location)
• 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;
Eg: $name=“Sunil”; 10
Example
<?php
$txt = "Hello World!";
$number = 16;
echo $txt;
echo $number;
?>
11
Variable Naming Rules
• A variable name must start with a letter or an
underscore "_"
• A variable name can only contain alpha-numeric
characters and underscores (a-Z, 0-9, and _ )
• A variable name should not contain spaces. If a
variable name is more than one word, it should
be separated with underscore ($my_string), or
with capitalization ($myString)
12
PHP String
• String variables are used for values that
contains character strings.
• Example 1:
<?php
$txt="Hello World";
echo $txt;
?>
The output of the code above will be:
Hello World
13
PHP String
• Example 2:
<?php
$txt1="Hello World";
$txt2="1234";
echo $txt1 . " " . $txt2;
?>
16
PHP Operators
• Comparison Operators
== is equal to 5==8 returns false
!= is not equal5!=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
17
Conditional Statements
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.
• Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
18
Conditional Statements
Example 1:
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
</body>
</html> 19
Conditional Statements
Example 2:
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
{
echo "Hello!<br />";
echo "Have a nice weekend!";
echo "See you on Monday!";
}
?>
</body>
</html>
20
Conditional Statements
• 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; 21
Conditional Statements
Example 3:
<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>
22
PHP Switch Statement
• If you want to select one of many blocks of
code to be executed, use the Switch
statement.
23
PHP Switch Statement
• 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;
}
24
PHP Switch Statement
Example:
<html>
<body>
<?php
$x=2;
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>
25
Exercise :
• Assign values to two variables. Use
comparison operators to test whether the first
value is
– The same as the second
– Less than the second
– Greater than the second
– Less than or equal to the second
• Print the result of each test to the browser.
• Change the values assigned to your test
variables and run the script again.
26
PHP Arrays
• 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.
27
PHP Arrays : Example 1
<?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 28
PHP Arrays : Example 2
<?php
$names = array("Peter","Quagmire","Joe");
echo $names[1] . " and " . $names[2] .
" are ". $names[0] . "'s neighbors";
?>
30
Multidimensional Arrays
• In a multidimensional array,
– each element in the main array can also be
an array.
– each element in the sub-array can be an
array, and so on
31
PHP Looping
• Looping statements in PHP are
used to execute the same block
of code a specified number of
times.
32
PHP Looping
• Looping statements in PHP are used to
execute the same block of code a
specified number of times.
• In PHP we have the following looping
statements:
– while - loops
– do...while - loops
– for - loops
– foreach - loops 33
The while Statement
• The while statement will execute a block of
code if and as long as a condition is true.
• Syntax
while (condition)
{
statement 1;
statement 2;
}
34
The while Statement
Example
.
.
.
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
.
.
.
35
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);
36
do...while Statement
• Example
.
.
$i=0;
do
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i<5);
.
. 37
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;
}
38
The for Statement
• Example
.
.
for ($i=1; $i<=5; $i++)
{
echo "Hello World!<br />";
}
.
.
39
The foreach Statement
• The foreach statement is used to loop through
arrays.
• Syntax
foreach (array as value)
{
code to be executed;
} 40
The foreach Statement
• Example
42
Example 1
A simple function that writes my name when it is called:
<html>
<body>
<?php
function writeMyName()
{
echo “Nimal";
}
writeMyName();
?>
</body>
</html>
43
Example 2
<html>
<body>
<?php
function writeMyName()
{
echo "Kai Jim Refsnes";
}
echo "Hello world!<br />";
echo "My name is ";
writeMyName();
echo ".<br />That's right, ";
writeMyName();
echo " is my name.";
?>
</body>
</html>
44
Example 3
• The following example will write different first names,
<html>
<body>
<?php
function writeMyName($fname)
{
echo $fname . " .<br />";
}
echo "My name is ";
writeMyName(“Nimal");
echo "My name is ";
writeMyName(“Kamal");
echo "My name is ";
writeMyName(“Amal");
?>
</body>
</html>
45
Example 4
• The following function has two parameters
<html>
<body>
<?php
function writeMyName($fname,$lname)
{
echo $fname . " Refsnes" . $lname . "<br />";
}
echo "My name is ";
writeMyName(“Nimal",“Amarasinghe");
echo "My name is ";
writeMyName(“Kamal",“Perera");
echo "My name is ";
writeMyName(“Amal",“Silva");
?>
</body>
</html> 46
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>
47
PHP Forms
• The PHP $_GET and $_POST variables
are used to retrieve information from
forms, like user input.
48
Example
• Welcome.htm
<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> 49
Example
• welcome.php
<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
50
PHP $_GET
• 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)
• It has limits on the amount of information
to send (max. 100 characters).
51
Example
<form action="welcome.php" method="get">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
• Welcome.php
52
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!
• The HTTP GET method is not suitable on
large variable values; the value cannot
exceed 100 characters.
53
PHP $_POST
• 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.
54
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>
• Welcome.php
Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old!
55
PHP Database
56
Connecting to a MySQL Database
• Before you can access and work with data in a database,
you must create a connection to the database.
• In PHP, this is done with the mysql_connect() function.
• Syntax
mysql_connect(servername,username,password);
58
Create MySQLDatabase and Tables
59
Example
• In the following example we create a database called "my_db":
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
mysql_close($con);
?>
60
Create a Table
• Example
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create table in my_db database
mysql_select_db("my_db", $con);
$sql = "CREATE TABLE person
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
mysql_query($sql,$con);
mysql_close($con);
61
Insert new records into a
database table
• Example
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("INSERT INTO person (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', '35')");
mysql_query("INSERT INTO person (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire', '33')");
mysql_close($con);
?>
62
Insert Data From a Form Into a
Database
• Example : insert.html
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
63
Insert Data From a Form Into a
Database
• Example : insert.php
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO person (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?> 64