SlideShare a Scribd company logo
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

PDF
Php a dynamic web scripting language
PPT
Php Lecture Notes
PPT
Prersentation
PPTX
PPT
PHP MySQL Workshop - facehook
Php a dynamic web scripting language
Php Lecture Notes
Prersentation
PHP MySQL Workshop - facehook

What's hot (20)

PPTX
Php basics
PPTX
Basic of PHP
PPTX
Php Tutorial
PPT
Php Crash Course
PPTX
Php Unit 1
PPT
Control Structures In Php 2
PDF
Materi Dasar PHP
PPTX
Dev traning 2016 basics of PHP
PDF
Web Development Course: PHP lecture 1
PPT
PHP complete reference with database concepts for beginners
PPT
Introduction to php php++
PPT
PHP POWERPOINT SLIDES
PPT
PHP - Introduction to PHP
PPT
PPT
Php(report)
PPT
Php i basic chapter 3
PPT
Basic PHP
PPTX
Php.ppt
PDF
PHP Loops and PHP Forms
Php basics
Basic of PHP
Php Tutorial
Php Crash Course
Php Unit 1
Control Structures In Php 2
Materi Dasar PHP
Dev traning 2016 basics of PHP
Web Development Course: PHP lecture 1
PHP complete reference with database concepts for beginners
Introduction to php php++
PHP POWERPOINT SLIDES
PHP - Introduction to PHP
Php(report)
Php i basic chapter 3
Basic PHP
Php.ppt
PHP Loops and PHP Forms
Ad

Similar to Intro to php (20)

PPTX
Lecture 6: Introduction to PHP and Mysql .pptx
PPTX
INTRODUCTION ON PHP - SERVER SIDE SCRIPTING LANGUAGE
PPTX
php Chapter 1.pptx
PDF
UNIT4.pdf php basic programming for begginers
PDF
Wt unit 4 server side technology-2
PPTX
FYBSC IT Web Programming Unit IV PHP and MySQL
PDF
WT_PHP_PART1.pdf
PPTX
PDF
1336333055 php tutorial_from_beginner_to_master
PPTX
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
PPTX
PHP Lecture 01 .pptx PHP Lecture 01 pptx
PPTX
Php unit i
DOCX
PHP NOTES FOR BEGGINERS
PPTX
PPTX
PPT
PHP - Web Development
DOCX
Basic php 5
DOCX
Free PHP Book Online | PHP Development in India
PPTX
PHP Basics
Lecture 6: Introduction to PHP and Mysql .pptx
INTRODUCTION ON PHP - SERVER SIDE SCRIPTING LANGUAGE
php Chapter 1.pptx
UNIT4.pdf php basic programming for begginers
Wt unit 4 server side technology-2
FYBSC IT Web Programming Unit IV PHP and MySQL
WT_PHP_PART1.pdf
1336333055 php tutorial_from_beginner_to_master
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
PHP Lecture 01 .pptx PHP Lecture 01 pptx
Php unit i
PHP NOTES FOR BEGGINERS
PHP - Web Development
Basic php 5
Free PHP Book Online | PHP Development in India
PHP Basics
Ad

More from Ahmed Farag (14)

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

Recently uploaded (20)

PDF
Sensors and Actuators in IoT Systems using pdf
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
NewMind AI Monthly Chronicles - July 2025
PPT
Teaching material agriculture food technology
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Electronic commerce courselecture one. Pdf
PPTX
Cloud computing and distributed systems.
PDF
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PDF
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Sensors and Actuators in IoT Systems using pdf
GamePlan Trading System Review: Professional Trader's Honest Take
NewMind AI Monthly Chronicles - July 2025
Teaching material agriculture food technology
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
MYSQL Presentation for SQL database connectivity
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
The Rise and Fall of 3GPP – Time for a Sabbatical?
Spectral efficient network and resource selection model in 5G networks
Electronic commerce courselecture one. Pdf
Cloud computing and distributed systems.
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
madgavkar20181017ppt McKinsey Presentation.pdf
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
Chapter 3 Spatial Domain Image Processing.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
How Onsite IT Support Drives Business Efficiency, Security, and Growth.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 [email protected]
  • 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', '[email protected]')"; 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); ?>