SlideShare a Scribd company logo
1 of 66
Intro to PHP
Ahmed Farag
Information Systems Dept.
Faculty of Computers and Information
Menoufia University, Egypt.
Intro
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.
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
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"
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
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
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
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
Basic PHP Syntax
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
?>
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>
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>
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>
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>
PHP 7 Variables
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>
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.
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;
?>
PHP 7 Data Types
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
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;
?>
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);
?>
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);
?>
PHP
Boolean
• A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
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);
?>
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);
?>
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);
?>
PHP 7 if...else...elseif Statements
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
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!";
}
?>
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!";
}
?>
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!";
}
?>
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;
}
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!";
}
?>
PHP 7 while Loops
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
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++;
}
?>
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);
?>
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);
?>
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>";
}
?>
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>";
}
?>
PHP 7 Arrays
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] . ".";
?>
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.
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();
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] . ".";
?>
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>";
}
?>
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.";
?>
Associati
ve Arrays
• PHP Associative Arrays
<?php
$age
= array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"
);
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
PHP 7 Form Handling
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>
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>
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
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>
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.
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!
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.
PHP 7 MySQL Database
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.
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";
?>
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
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);
?>
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);
?>
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);
?>
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);
?>

More Related Content

What's hot (20)

Php basics
Php basicsPhp basics
Php basics
 
Basic of PHP
Basic of PHPBasic of PHP
Basic of PHP
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Php Crash Course
Php Crash CoursePhp Crash Course
Php Crash Course
 
Introduction to php basics
Introduction to php   basicsIntroduction to php   basics
Introduction to php basics
 
Php Unit 1
Php Unit 1Php Unit 1
Php Unit 1
 
Control Structures In Php 2
Control Structures In Php 2Control Structures In Php 2
Control Structures In Php 2
 
Materi Dasar PHP
Materi Dasar PHPMateri Dasar PHP
Materi Dasar PHP
 
Dev traning 2016 basics of PHP
Dev traning 2016   basics of PHPDev traning 2016   basics of PHP
Dev traning 2016 basics of PHP
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1
 
PHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginnersPHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginners
 
Introduction to php php++
Introduction to php php++Introduction to php php++
Introduction to php php++
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
 
PHP - Introduction to PHP
PHP -  Introduction to PHPPHP -  Introduction to PHP
PHP - Introduction to PHP
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
Php(report)
Php(report)Php(report)
Php(report)
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
Basic PHP
Basic PHPBasic PHP
Basic PHP
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
PHP Loops and PHP Forms
PHP  Loops and PHP FormsPHP  Loops and PHP Forms
PHP Loops and PHP Forms
 

Similar to Intro to php (20)

php Chapter 1.pptx
php Chapter 1.pptxphp Chapter 1.pptx
php Chapter 1.pptx
 
Wt unit 4 server side technology-2
Wt unit 4 server side technology-2Wt unit 4 server side technology-2
Wt unit 4 server side technology-2
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
 
WT_PHP_PART1.pdf
WT_PHP_PART1.pdfWT_PHP_PART1.pdf
WT_PHP_PART1.pdf
 
Php Basics
Php BasicsPhp Basics
Php Basics
 
Php
PhpPhp
Php
 
1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
 
Php unit i
Php unit iPhp unit i
Php unit i
 
PHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERSPHP NOTES FOR BEGGINERS
PHP NOTES FOR BEGGINERS
 
Php
PhpPhp
Php
 
Php1
Php1Php1
Php1
 
PHP - Web Development
PHP - Web DevelopmentPHP - Web Development
PHP - Web Development
 
Basic php 5
Basic php 5Basic php 5
Basic php 5
 
Free PHP Book Online | PHP Development in India
Free PHP Book Online | PHP Development in IndiaFree PHP Book Online | PHP Development in India
Free PHP Book Online | PHP Development in India
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)basic concept of php(Gunikhan sonowal)
basic concept of php(Gunikhan sonowal)
 
Lecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdfLecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdf
 
Php basic for vit university
Php basic for vit universityPhp basic for vit university
Php basic for vit university
 
Phphacku iitd
Phphacku iitdPhphacku iitd
Phphacku iitd
 

More from Ahmed Farag

Sql modifying data - MYSQL part I
Sql modifying data - MYSQL part ISql modifying data - MYSQL part I
Sql modifying data - MYSQL part IAhmed Farag
 
MYSQL using set operators
MYSQL using set operatorsMYSQL using set operators
MYSQL using set operatorsAhmed Farag
 
MYSQL single rowfunc-multirowfunc-groupby-having
MYSQL single rowfunc-multirowfunc-groupby-havingMYSQL single rowfunc-multirowfunc-groupby-having
MYSQL single rowfunc-multirowfunc-groupby-havingAhmed Farag
 
Introduction to NoSQL and MongoDB
Introduction to NoSQL and MongoDBIntroduction to NoSQL and MongoDB
Introduction to NoSQL and MongoDBAhmed Farag
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP conceptsAhmed Farag
 
Introduction to object-oriented analysis and design (OOA/D)
Introduction to object-oriented analysis and design (OOA/D)Introduction to object-oriented analysis and design (OOA/D)
Introduction to object-oriented analysis and design (OOA/D)Ahmed Farag
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams Ahmed Farag
 
intro to pointer C++
intro to  pointer C++intro to  pointer C++
intro to pointer C++Ahmed Farag
 

More from Ahmed Farag (14)

MYSql manage db
MYSql manage dbMYSql manage db
MYSql manage db
 
Normalization
NormalizationNormalization
Normalization
 
Sql modifying data - MYSQL part I
Sql modifying data - MYSQL part ISql modifying data - MYSQL part I
Sql modifying data - MYSQL part I
 
MYSQL using set operators
MYSQL using set operatorsMYSQL using set operators
MYSQL using set operators
 
MYSQL join
MYSQL joinMYSQL join
MYSQL join
 
MYSQL single rowfunc-multirowfunc-groupby-having
MYSQL single rowfunc-multirowfunc-groupby-havingMYSQL single rowfunc-multirowfunc-groupby-having
MYSQL single rowfunc-multirowfunc-groupby-having
 
Introduction to NoSQL and MongoDB
Introduction to NoSQL and MongoDBIntroduction to NoSQL and MongoDB
Introduction to NoSQL and MongoDB
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP concepts
 
Introduction to object-oriented analysis and design (OOA/D)
Introduction to object-oriented analysis and design (OOA/D)Introduction to object-oriented analysis and design (OOA/D)
Introduction to object-oriented analysis and design (OOA/D)
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
OOP C++
OOP C++OOP C++
OOP C++
 
Functions C++
Functions C++Functions C++
Functions C++
 
intro to pointer C++
intro to  pointer C++intro to  pointer C++
intro to pointer C++
 
Intro to C++
Intro to C++Intro to C++
Intro to C++
 

Recently uploaded

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 

Recently uploaded (20)

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 

Intro to php

  • 1. Intro to PHP Ahmed Farag Information Systems Dept. Faculty of Computers and Information Menoufia University, Egypt.
  • 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; ?>
  • 20. PHP 7 Data Types
  • 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!"; } ?>
  • 36. PHP 7 while Loops
  • 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."; ?>
  • 50. Associati ve Arrays • PHP Associative Arrays <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43" ); foreach($age as $x => $x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>"; } ?>
  • 51. PHP 7 Form Handling
  • 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.
  • 59. PHP 7 MySQL Database
  • 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); ?>