Unit 3&4
Unit 3&4
(CSE 208 )
( 1I/4 B.Tech-CSE)
Unit- III
❑ Overview of PHP
PHP scripts are executed on the server
It is free to download and use It is powerful enough to be at the core of
the biggest blogging system on the web (WordPress)!
It is deep enough to run the largest social network (Facebook)!
It is also easy enough to be a beginner's first server side language!
Runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
Compatible with almost all servers used today (Apache, IIS, Wamp etc)
Supports a wide range of databases
Easy to learn and runs efficiently on the server side
5
Overview of PHP
❑ Overview of PHP
generate dynamic page content
create, open, read, write, delete, and close files on the server
collect form data
send and receive cookies
add, delete, modify data in your database
be used to control user-access
encrypt data
PHP Language is NOT Case Sensitive. For example, print & PRINT mean the
same. However, the variables are case sensitive. $num & $Num are treated as
different variables.
PHP is a Loosely Typed Language.
6
Overview of PHP
❑ PHP Scripts
■ PHP is server side scripting, very good for creating dynamic
content
■ Syntax based on Perl, Java, and C
■ Typically file ends in .php
?> tag
■ Separated in files with the <?php
■ php commands can make up an entire file, or can be contained
in html-
-this is a choice….
■ Program statements ends with semicolon ";"
7
Overview of PHP
❑ Creating & Running PHP
Script
PHP is a server-side scripting language. So, to run PHP scripts,
you need to install PHP and a. web-server software like Apache /
Wamp / Xamp. For scripting using databases, a DBMS such as
MySQL should be installed.
The most compatible options include PHP + Apache / Wamp +
MySQL
The PHP files (.php files) should be copied to a particular folder
(htdocs or html or www etc.) where the webpages need to be
hosted.
8
Overview of PHP
We've talk about how the browser can read a text file and
process it, that's a basic parsing method
10
Overview of PHP
❑ Two Ways to parse PHP
■ You can embed sections of php inside html:
<html>
<body>
<?php
$myvar = "Hello World!";
echo $myvar;
?>
</body>
</html>
11
Overview of PHP
<?php
echo "<html><h1>SRM AP</h1></html>"
?>
<?php
// This is a single-line comment
/* This is a
multi-line comment */
?>
13
Overview of PHP
❑ PHP Variables
<?php
$txt1 = "Learn PHP";
$txt2 = “at SRM AP";
$x = 5;
$y = 4;
17
Overview of PHP
❑ PHP echo and print Statements
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello SRM AP!<br>";
print "I am CSE-C Student!";
?>
<?php
$txt1 = “Hello SRM";
$txt2 = “I am CSE-C Student";
$x = 49;
$y = 59;
print "<h2>" . $txt1 . "</h2>";
print "Study PHP at " . $txt2 . "<br>";
print $x + $y;
?>
18
Overview of PHP
❑ Data Types
var_dump($x);
echo "<br>";
var_dump($y);
echo "<br>";
var_dump($z);
?>
</body>
</html>
20
Overview of PHP
❑ PHP Constants
A constant is an identifier (name) for a simple value. The value
cannot be changed during the script.
define(name, value,
case-insensitive);
name: Specifies the name of the constant
value: Specifies the value of the constant
case-insensitive: Specifies whether the constant
name should be case-insensitive. 21
Overview of PHP
❑ PHP Constants
<html>
<body>
<?php
// case-sensitive constant name
define("GREETING", "Welcome to SRM AP
CSE!");
echo GREETING;
?>
</body>
</html>
<?php
// case-insensitive constant name
define("GREETING", "Welcome to SRM AP
CSE!", true);
echo greeting;
?> 22
Overview of PHP
❑ Operators
■ Arithmetic Operators: +, -, *,/ , %, ++,
--
■ Assignment Operators: =, +=, -=, *=, /=,
%=
■ Comparison Operators: ==, !=, >, <, >=,
<=
■ Logical Operators: &&, ||, !
■ String Operators: . and .= (for string concatenation)
Example
Is the same as
x+=y x=x+y
x-=y x=x-y
x=x*y
x*=y x=x/y
x/=y x=x%y
x%=y 23
Overview of PHP
❑ Operators
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
$a = "Hello ";
$a .= "World!";
24
Overview of PHP
❑ Operators Example
<html>
<body>
<?php
$x = 10;
$y = 6;
echo $x + $y;
echo "<br>";
echo $x - $y;
?>
</body>
</html>
25
PHP Examples
<html>
<head>
<title>Hello World</title>
</head>
<body>
<p>This is going to be ignored by the PHP interpreter.</p>
<?php
echo "<p>While this is going to be parsed.</p>";
?>
<p>This will also be ignored by the PHP preprocessor.</p>
<?php
print("<p>Hello and welcome to <i>my</i> page!</p>");
?>
<?php
//This is a comment
?>
</body>
</html>
26
Overview of PHP
27
Overview of PHP
❑ PHP
while Loops
- 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
The break statement can be used to jump out
array
of a for loop.
The continue statement stops the current iteration in
the for loop and continue with the next.
28
Overview of PHP
<html> <html>
<body> <body>
<?php <?php
for ($x = 0; $x < 10; $x++) { for ($x = 0; $x < 10; $x++) {
if ($x == 4) { if ($x == 4) {
continue; break;
} }
echo "The number is: $x echo "The number is: $x
<br>"; <br>";
} }
?> ?>
</body> </body>
</html> </html> 29
Overview of PHP
❑ PHP Arrays
An array is a special variable that can hold many values under a
single name, and you can access the values by referring to an
index number or name.
In PHP, there are three types of arrays:
•Indexed arrays - Arrays with a numeric index - In indexed arrays
each item has an index number.
•Associative arrays - Arrays with named keys - Associative arrays
are arrays that use named keys that you assign to them.
•Multidimensional arrays - Arrays containing one or more arrays
- 30
Overview of PHP
❑ Indexed arrays
<html>
<body>
<?php
$cars = array(“Siva", “Rama",
“Krishna");
echo $cars[0];
echo $cars[2];
?>
</body>
</html>
31
Overview of PHP
❑ Associative arrays
<html>
<body>
<?php
$car = array("brand"=>“BMW", "model"=>“Series7",
"year"=>2024);
echo $car["model"];
?>
</body>
</html>
32
Overview of PHP
❑ Multidimensional arrays
<html>
<body>
<?php
$student = array (
array("Siva",85,"A"),
array("Rama",80,"B"),
array("Krishna",90,"O"),
array("Pavan",85,"A")
);
echo $student[0][0].": Marks: ".$student[0][1].", Grade:
".$student[0][2].".<br>";
echo $student[1][0].": Marks: ".$student[1][1].", Grade:
".$student[1][2].".<br>";
echo $student[2][0].": Marks: ".$student[2][1].", Grade:
".$student[2][2].".<br>";
echo $student[3][0].": Marks: ".$student[3][1].", Grade:
".$student[3][2].".<br>"; 33
Overview of PHP
❑ PHP Array Functions
The count() function returns the number of elements in an
array.
The current() function returns the value of the current element
in an array.
The range() function creates an array containing a range of
elements.
The next() function moves the internal pointer to, and outputs,
the next element in the array.
The prev() function moves the internal pointer to, and outputs,
34
the previous element in the array.
Overview of PHP
PHP array sort functions:
• sort() - sort arrays in ascending order
• rsort() - sort arrays in descending order
• asort() - sort associative arrays in ascending order, according to
the value
• ksort() - sort associative arrays in ascending order, according to
the key
• arsort() - sort associative arrays in descending order, according
to the value
• krsort() - sort associative arrays in descending order, according
35
to the key
Overview of PHP
<html>
<body>
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++)
echo $numbers[$x]." ";
echo "<br>";
rsort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++)
echo $numbers[$x]." ";
?>
</body>
</html>
36
Overview of PHP
❑ Superglobals
Some predefined variables in PHP are "superglobals", which means
that they are always accessible, regardless of scope - and you can
access them from any function, class or file without having to do
anything special.
37
Overview of PHP
❑ $GLOBALS
$GLOBALS is a PHP super global variable which is used to access
global variables from anywhere in the PHP script (also from within
functions or methods). PHP stores all global variables in an array
called $GLOBALS[index]. The index holds the name of the variable.
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] +
$GLOBALS['y'];
}
addition();
echo $z;
?> 38
Overview of PHP
❑ $_SERVER
$_SERVER is a PHP super global variable which holds information
about headers, paths, and script locations.
39
Overview of PHP
<?php
echo
$_SERVER['PHP_SELF']."<br>";
echo
$_SERVER['SERVER_NAME']."<br
>";
echo
$_SERVER['HTTP_HOST']."<br>";
echo
$_SERVER['SERVER_SOFTWARE'
40
]."<br>";
Overview of PHP
❑ $_REQUEST
$_REQUEST is a PHP super global variable which is used to collect
data after submitting an HTML form.
This example below shows a form with an input field and a submit
button. When a user submits the data by clicking on "Submit", the form
data is sent to the file specified in the action attribute of the <form> tag.
In this example, we point to this file itself for processing form data. If
you wish to use another PHP file to process form data, replace that with
the filename of your choice. Then, we can use the super global variable
$_REQUEST to collect the value of the input field.
41
Overview of PHP
❑ $_POST
$_POST is a PHP super global variable which is used to collect
form data after submitting an HTML form with method="post".
$_POST is also widely used to pass variables.
This example below shows a form with an input field and a submit
button. When a user submits the data by clicking on "Submit", the
form data is sent to the file specified in the action attribute of the
<form> tag.
In this example, we point to the file itself for processing form data.
If you wish to use another PHP file to process form data, replace
that with the filename of your choice. Then, we can use the super
global variable $_POST to collect the value of the input field. 43
Overview of PHP
<?php
if
($_SERVER["REQUEST_METHOD"
] == "POST")
{
// collect value of input field
$name = $_POST['fname'];
if (empty($name))
echo "Name is empty";
else
echo $name;
}
?>
44
Overview of PHP
❑ $_GET
45
Overview of PHP
getmethodex.php:
47
Overview of PHP
48
Overview of PHP
❑ Functions
Built-in Functions : PHP has over 1000 built-in functions that can
be called directly, from within a script, to perform a specific task.
Syntax
function functionName()
{
code to be executed;
}
<html>
<body>
<?php
function writeMsg()
{
echo “Welcome to SRM AP";
}
writeMsg();
?>
</body>
</html>
50
Overview of PHP
❑ Example
<?php
function Name($fname,
$year)
{
echo "$fname Born in
$year <br>";
}
Name("RAM","Treta
Yuga");
Name("Lakshman","Treta
Yuga");
?> 51
Overview of PHP
❑ Default Argument Value
The following example shows how to use a default parameter. If we
call the function setHeight() without arguments it takes the default
value as argument.
<?php
function setHeight($minheight = 50)
{
echo "The height is : $minheight
<br>";
}
setHeight(350);
setHeight();
setHeight(80);
?>
52
Overview of PHP
❑ Using return statement:
<?php
function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5,10) .
"<br>";
echo "7 + 13 = " . sum(7,13) .
"<br>";
echo "2 + 4 = " . sum(2,4);
?>
53
Overview of PHP
❑ Parameter passing to
Functions:
PHP allows us two ways in which an argument can be passed into a
function:
Pass by Value: On passing arguments using pass by value, the
value of the argument gets changed within a function, but the
original value outside the function remains unchanged. That
means a duplicate of the original value is passed as an argument.
Pass by Reference: On passing arguments as pass by reference,
the original value is passed. Therefore, the original value gets
altered. In pass by reference we actually pass the address of the
54
value, where it is stored using ampersand sign(&).
Overview of PHP
❑ Example
55
Overview of PHP
❑ Pattern matching in PHP
Function Description
preg_match Returns 1 if the pattern was found in the string and 0
() if not
preg_match Returns the number of times the pattern was found in
_all() the string, which may also be 0
preg_replac Returns a new string where matched patterns have
e() been replaced with another string
57
Overview of PHP
58
Overview of PHP
❑ Form Handling
59
Overview of PHP
❑ Example:
60
Overview of PHP
❑ Cookies:
A cookie is often used to identify a user. A cookie is a small file that
the server embeds on the user's computer. Each time the same
computer requests a page with a browser, it will send the cookie
too. With PHP, you can both create and retrieve cookie values. A
cookie is created with the setcookie() function.
Create/Retrieve a Cookie :
The following example creates a cookie named "user" with the
value "XYZ". The cookie will expire after 30 days (3600 * 30). The
"/" means that the cookie is available in entire website (otherwise,
select the directory you prefer). 61
Overview of PHP
❑ Cookies:
We then retrieve the value of the cookie "user" (using the global
variable $_COOKIE).
We also use the isset() function to find out if the cookie is set.
The setcookie() function must appear BEFORE the <html> tag.
62
Overview of PHP
❑ Cookie Creation:
63
Overview of PHP
64
Overview of PHP
65
Overview of PHP
❑ Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration
date in the past.
66
Overview of PHP
❑ Sessions
In general, session refers to a frame of communication between two
mediums. A PHP session is used to store data on a server rather
than the computer of the user. Session identifiers or SID is a
unique number which is used to identify every user in a session
based environment. The SID is used to link the user with his
information on the server like posts, emails etc.
68
Overview of PHP
❑ Start a PHP Session
<?php
// Start the session
session_start();
?>
69
Overview of PHP
❑ Storing Session Data
70
Overview of PHP
<?php
// Start the session
session_start();
?>
<html>
<body>
<?php
// Set session variables
$_SESSION["Rollnumber"] = "11";
$_SESSION["Name"] = "XYZ";
echo "Session variables are set.";
?>
</body>
</html>
71
Overview of PHP
<?php
session_start();
?>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo 'The Name of the student is :' . $_SESSION["Name"] .
'<br>’;
echo 'The Roll number of the student is :' .
$_SESSION["Rollnumber"] . '<br>';
?>
</body>
</html>
73
Overview of PHP
❑ Destroying Session: To delete only a certain session data, the
unset feature can be used with the corresponding session variable
in the $_SESSION associative array.
74
Overview of PHP
<?php
session_start();
?>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
echo "All session variables are now removed,
and the session is destroyed."
?>
</body>
</html>
75
Overview of PHP
PHP Filters
The PHP filter extension has many of the functions needed for
checking user input, and is designed to make data validation easier
and quicker.
The filter_list() function can be used to list what the PHP filter
extension offers:
76
Overview of PHP
<html> <table>
<head> <tr>
<style> <td>Filter Name</td>
table, th, td { <td>Filter ID</td>
border: 1px solid </tr>
black; <?php
border-collapse: foreach (filter_list() as $id
collapse; =>$filter) {
} echo '<tr><td>' . $filter .
th, td { '</td><td>' . filter_id($filter) .
padding: 5px; '</td></tr>';
} }
</style> ?>
</head> </table>
<body> 77
Overview of PHP
PHP filter_var() Function
The filter_var() function both validate and sanitize data.
Validate an Integer:
The following example uses the filter_var() function to check if the
variable $int is an integer. If $int is an integer, the output of the code
below will be: "Integer is valid". If $int is not an integer, the output
will be: "Integer is not valid":
79
Overview of PHP
<html>
<body>
<?php
$int = 100;
Output: if (!filter_var($int,
FILTER_VALIDATE_INT) === false) {
Integer is echo("Integer is valid");
} else {
valid echo("Integer is not valid");
}
?>
</body>
</html>
80
Overview of MySQL
❑ MySQL Database:
81
Overview of MySQL
❑ MySQL Database:
MySQL is a database system used on the web
MySQL is a database system that runs on a server
MySQL is ideal for both small and large applications
MySQL is very fast, reliable, and easy to use
MySQL uses standard SQL
MySQL compiles on a number of platforms
MySQL is free to download and use
MySQL is developed, distributed, and supported by Oracle
Corporation
82
Overview of MySQL
❑ MySQL Database:
Database Queries:
A query is a question or a request.
We can query a database for specific information and have a
recordset returned.
83
Overview of MySQL
❑ MySQL Database:
85
Overview of MySQL
❑ MySQL Database:
86
Overview of MySQL
Create Table: The CREATE TABLE statement is used to create a
table in MySQL. We will create a table named "Employee", with
four columns: "id", "firstname", "lastname", "email".
87
Overview of MySQL
❑ Insert Data:
After a database and a table have been created, we can insert data
in the table.
88
Overview of MySQL
❑ Insert Data:
89
Overview of MySQL
Select Data:
90
Overview of MySQL
❑ Select Data:
91
Overview of MySQL
❑ MySQL Database:
WHERE Clause:
92
Overview of MySQL
❑ MySQL Database:
ORDER BY Clause :
Delete Data :
94
Overview of MySQL
❑ MySQL Database:
Update Data:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value