3. Intro to
PHP
• PHP is a server scripting language, and a powerful tool for
making dynamic and interactive Web pages.
• PHP is a widely-used, free, and efficient alternative to
competitors such as Microsoft's ASP.
• PHP 7 is the latest stable release.
4. What is
PHP?
• PHP is an acronym for "PHP: Hypertext Preprocessor"
• PHP is a widely-used, open source scripting language
• PHP scripts are executed on the server
• PHP is free to download and use
5. What is a
PHP File?
• PHP files can contain text, HTML, CSS, JavaScript, and PHP
code
• PHP code are executed on the server, and the result is
returned to the browser as plain HTML
• PHP files have extension ".php"
6. What
Can PHP
Do?
• PHP can generate dynamic page content
• PHP can create, open, read, write, delete, and close files on
the server
• PHP can collect form data
• PHP can add, delete, modify data in your database
• PHP can be used to control user-access
• PHP can encrypt data
7. What
Can PHP
Do?
• PHP can generate dynamic page content
• PHP can create, open, read, write, delete, and close files on
the server
• PHP can collect form data
• PHP can add, delete, modify data in your database
• PHP can be used to control user-access
• PHP can encrypt data
8. Why
PHP?
• PHP runs on various platforms (Windows, Linux, Unix, Mac OS
X, etc.)
• PHP supports a wide range of databases
• PHP is free. Download it from the official PHP resource:
www.php.net
• PHP is easy to learn and runs efficiently on the server side
9. What Do
I Need?
• To start using PHP, you can:
1. Find a web host with PHP and MySQL support
2. Install a web server on your own PC, and then install
PHP and MySQL (Xampp)
• Set Up PHP on Your Own PC
• install a web server
• install PHP
• install a database, such as MySQL
11. Basic
PHP
Syntax
• A PHP script is executed on the server, and the plain HTML
result is sent back to the browser.
• A PHP script can be placed anywhere in the document.
• A PHP script starts with <?php and ends with ?>:
• The default file extension for PHP files is ".php".
• A PHP file normally contains HTML tags, and some PHP
scripting code.
<?php
// PHP code goes here
?>
12. Example
• Note: PHP statements end with a semicolon (;).
• Below, we have an example of a simple PHP file, with a PHP
script that uses a built-in PHP function "echo" to output the
text "Hello World!" on a web page:
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
13. Commen
ts in PHP
• A comment in PHP code is a line that is not read/executed as
part of the program. Its only purpose is to be read by
someone who is looking at the code.
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
// You can also use comments to leave out parts
of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body>
</html>
14. Basic
PHP
Syntax
• PHP Case Sensitivity:
• In PHP, NO keywords (e.g. if, else, while, echo, etc.),
classes, functions, and user-defined functions are case-
sensitive.
• In the example below, all three echo statements below
are legal (and equal):
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
15. Basic
PHP
Syntax
• However; all variable names are case-sensitive.
• In the example below, only the first statement will display the
value of the $color variable (this is because $color, $COLOR,
and $coLOR are treated as three different variables):
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
17. Variables
• Variables are "containers" for storing information.
• In PHP, a variable starts with the $ sign, followed by the name
of the variable:
<html>
<body>
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>
</body>
</html>
18. Variables
• Note: When you assign a text value to a variable, put quotes
around the value.
• Note: Unlike other programming languages, PHP has no
command for declaring a variable. It is created the moment
you first assign a value to it.
• Think of variables as containers for storing data.
19. Variables
• Output Variables:
• The PHP echo statement is often used to output data to
the screen.
• The following example will show how to output text and a
variable:
<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>
<?php
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
?>
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
21. Data
Types
• Variables can store data of different types, and different data
types can do different things.
• PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
22. PHP
String
• A string is a sequence of characters, like "Hello world!".
• A string can be any text inside quotes. You can use single or
double quotes:
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
23. PHP
Integer
• An integer data type is a non-decimal number between -
2,147,483,648 and 2,147,483,647.
• Rules for integers:
• An integer must have at least one digit
• An integer must not have a decimal point
• An integer can be either positive or negative
• Integers can be specified in three formats: decimal (10-
based), hexadecimal (16-based - prefixed with 0x) or
octal (8-based - prefixed with 0)
• In the following example $x is an integer. The PHP var_dump()
function returns the data type and value:
<?php
$x = 5985;
var_dump($x);
?>
24. PHP Float
• A float (floating point number) is a number with a decimal
point.
• In the following example $x is a float. The PHP var_dump()
function returns the data type and value:
<?php
$x = 10.365;
var_dump($x);
?>
25. PHP
Boolean
• A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
26. PHP
Array
• An array stores multiple values in one single variable.
• In the following example $cars is an array. The PHP
var_dump() function returns the data type and value:
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
27. PHP
NULL
Value
• A variable of data type NULL is a variable that has no value
assigned to it.
• Tip: If a variable is created without a value, it is automatically
assigned a value of NULL.
• Variables can also be emptied by setting the value to NULL:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
28. PHP
NULL
Value
• A variable of data type NULL is a variable that has no value
assigned to it.
• Tip: If a variable is created without a value, it is automatically
assigned a value of NULL.
• Variables can also be emptied by setting the value to NULL:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
30. if...else...
elseif
Statemen
ts
• Conditional statements are used to perform different actions
based on different conditions.
• In PHP we have the following conditional statements:
• if statement - executes some code if one condition is true
• if...else statement - executes some code if a condition is true
and another code if that condition is false
• if...elseif...else statement - executes different codes for more
than two conditions
• switch statement - selects one of many blocks of code to be
executed
31. if
• PHP - The if Statement
• The example below will output "Have a good day!" if the
current time (HOUR) is less than 20:
if (condition) {
code to be executed if condition is true;
}
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
?>
32. if...else
• The example below will output "Have a good day!" if the
current time is less than 20, and "Have a good night!"
otherwise:
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
33. if...elseif..
.else
• The example below will output "Have a good morning!" if the
current time is less than 10, and "Have a good day!" if the
current time is less than 20. Otherwise it will output "Have a
good night!":
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this
condition is true;
} else {
code to be executed if all conditions are false;
}
<?php
$t = date("H");
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
34. switch
• The switch statement is used to perform different actions
based on different conditions.
• Use the switch statement to select one of many blocks of
code to be executed.
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different
from all labels;
}
35. switch
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither
red, blue, nor green!";
}
?>
37. 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 code-lines in a script, we can use loops to
perform a task like this.
• while - loops through a block of code as long as the specified
condition is true
• do...while - loops through a block of code once, and then
repeats the loop as long as the 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
38. PHP
Loops
• The example below first sets a variable $x to 1 ($x = 1). Then,
the while loop will continue to run as long as $x is less than, or
equal to 5 ($x <= 5). $x will increase by 1 each time the loop
runs ($x++):
while (condition is true) {
code to be executed;
}
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
39. PHP
Loops
• The example below first sets a variable $x to 1 ($x = 1). Then,
the do while loop will write some output, and then increment
the variable $x with 1. Then the condition is checked (is $x
less than, or equal to 5?), and the loop will continue to run as
long as $x is less than, or equal to 5:
do {
code to be executed;
} while (condition is true);
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
40. PHP
Loops
• Notice that in a do while loop the condition is tested AFTER
executing the statements within the loop. This means that the
do while loop would execute its statements at least once,
even if the condition is false the first time.
• The example below sets the $x variable to 6, then it runs the
loop, and then the condition is checked:
<?php
$x = 6;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
41. PHP
Loops
• Parameters:
• init counter: Initialize the loop counter value
• test counter: Evaluated for each loop iteration. If it evaluates to
TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
• increment counter: Increases the loop counter value
• The example below displays the numbers from 0 to 10:
for (init counter; test counter; increment
counter) {
code to be executed;
}
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
42. PHP
Loops
• The foreach loop works only on arrays, and is used to loop
through each key/value pair in an array.
• For every loop iteration, the value of the current array
element is assigned to $value and the array pointer is moved
by one, until it reaches the last array element.
• The following example demonstrates a loop that will output
the values of the given array ($colors):
<?php
$colors
= array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
44. PHP 7
Arrays
• An array stores multiple values in one single variable:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . "
and " . $cars[2] . ".";
?>
45. What is
an Array?
• An array is a special variable, which can hold more than one
value at a time.
• 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 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
• 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 solution is to create an array!
• An array can hold many values under a single name, and you
can access the values by referring to an index number.
46. Create an
Array in
PHP
• In PHP, the array() function is used to create an array:
• In PHP, there are three types of arrays:
• Indexed arrays - Arrays with a numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more
arrays
array();
47. Indexed
Arrays
• PHP Indexed Arrays
• There are two ways to create indexed arrays:
• The index can be assigned automatically (index always starts
at 0), like this:
$cars = array("Volvo", "BMW", "Toyota");
• or the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
• The following example creates an indexed array named $cars,
assigns three elements to it, and then prints a text containing
the array values:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . "
and " . $cars[2] . ".";
?>
48. Indexed
Arrays
• The count() function is used to return the length (the number
of elements) of an array:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
• Loop Through an Indexed Array
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
49. Associati
ve Arrays
• PHP Associative Arrays
• Associative arrays are arrays that use named keys that you
assign to them.
• There are two ways to create an associative array:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
• or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
<?php
$age
= array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
52. Form
Handling
• The PHP superglobals $_GET and $_POST are used to collect
form-data.
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
53. Form
Handling
• The PHP superglobals $_GET and $_POST are used to collect
form-data.
• When the user fills out the form above and clicks the submit
button, the form data is sent for processing to a PHP file
named "welcome.php". The form data is sent with the HTTP
POST method.
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
54. Form
Handling
• To display the submitted data you could simply echo all the
variables. The "welcome.php" looks like this:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
The output could be something like this:
Welcome John
Your email address is john.doe@example.com
55. Form
Handling
• The same result could also be achieved using the HTTP GET
method:
<html>
<body>
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
and "welcome_get.php" looks like this:
<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>
56. GET vs.
POST
• Both GET and POST create an array (e.g. array( key1 =>
value1, key2 => value2, key3 => value3, ...)). This array holds
key/value pairs, where keys are the names of the form
controls and values are the input data from the user.
• Both GET and POST are treated as $_GET and $_POST.
• $_GET is an array of variables passed to the current script via
the URL parameters.
• $_POST is an array of variables passed to the current script via
the HTTP POST method.
57. GET vs.
POST
• When to use GET?
• Information sent from a form with the GET method is visible
to everyone (all variable names and values are displayed in
the URL).
• GET also has limits on the amount of information to send.
The limitation is about 2000 characters. However, because the
variables are displayed in the URL, it is possible to bookmark
the page. This can be useful in some cases.
• GET may be used for sending non-sensitive data.
• Note: GET should NEVER be used for sending passwords or
other sensitive information!
58. GET vs.
POST
• When to use POST?
• Information sent from a form with the POST method is
invisible to others (all names/values are embedded within
the body of the HTTP request) and has no limits on the
amount of information to send.
• Moreover POST supports advanced functionality such as
support for multi-part binary input while uploading files to
server.
• However, because the variables are not displayed in the URL,
it is not possible to bookmark the page.
60. Connect
to
MySQL
• PHP 5 and later can work with a MySQL database using:
1. MySQLi extension (the "i" stands for improved)
2. PDO (PHP Data Objects)
• PDO will work on 12 different database systems, whereas
MySQLi will only work with MySQL databases.
• So, if you have to switch your project to use another database,
PDO makes the process easy. You only have to change the
connection string and a few queries. With MySQLi, you will
need to rewrite the entire code - queries included.
• Both support Prepared Statements. Prepared Statements
protect from SQL injection, and are very important for web
application security.
61. Connect
to
MySQL
• Before we can access data in the MySQL database, we need to
be able to connect to the server:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
62. PHP 7
Insert
Data Into
MySQL
• After a database and a table have been created, we can start
adding data in them.
• Here are some syntax rules to follow:
• The SQL query must be quoted in PHP
• String values inside the SQL query must be quoted
• Numeric values must not be quoted
• The word NULL must not be quoted
63. PHP 7
Insert
Data Into
MySQL
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password,
$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
64. Select
Data
From a
MySQL
Database
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password,
$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " .
$row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
65. Delete
Data From
a MySQL
Table
Using
MySQLi
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password,
$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
66. Update
Data In a
MySQL
Table
Using
MySQLi
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password,
$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>