SlideShare a Scribd company logo
1 of 45
Download to read offline
IT2253 Web Essentials
Unit IV – Server-Side Processing and Scripting-PHP
Kaviya.P
Kamaraj College of Engineering & Technology
Unit IV – Server-Side Processing and Scripting-PHP
PHP – Working principle of PHP – PHP Variables – Constants –
Operators – Flow Control and Looping – Arrays – Strings –
Functions – File Handling – File Uploading – Email Basics –
Email with attachments – PHP and HTML – Simple PHP scripts
– Databases with PHP.
PHP – Introduction
• Developed in 1994 by Apache Group.
• PHP: Hypertext Preprocessor.
• A server scripting language.
• Mainly used for form handling and database access.
• A powerful tool for making dynamic and interactive
webpages.
PHP – Introduction
Advantages
• Very simple and easy to learn
• Interpreted Language
• Open source
• Platform Independent
• Can directly integrated with HTML
• Support to design dynamic web applications
• Reliable, efficient and flexible scripting language
• Provides support for file system, managing user sessions, cookies, E-mail
Management, execute the system commands, create directories, etc.,
PHP – Introduction
Syntax
The code must be enclosed with in:
<?php
// Statements (or) Codes
?>
• If anyone wants to refer file then “inlude” construct is used.
Example: Include(“myfile.html”)
Comments
// 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
*/
Working Principle of PHP
• The most popular way of installing PHP is using XAMPP.
• XAMPP is a free distribution package that makes it easy to install Apache
Web Server, MySQL, PHP, PEAR.
1. Go to the site: https://www.apachefriends.org/index.html
2. Click on download XAMPP for Windows or Linux depending on the OS
3. When prompted for the download, click “Save” and wait for the download
finish.
4. Install the program and click on “Run”. Accept default settings by clicking
“Next” button. Finally, installation completion message is displayed.
5. On the drive, the XAMPP folder will be created. Click on xampp_start
file, this will enable to start Apache, MySQL and Tomcat start.
Working Principle of PHP
6. The control panel for XAMPP will look like this,
6. Write a PHP script and save it in C:XAMPPhtdocsphp-examples folder
by giving the filename and extension as .php.
7. Open the web browser and type http://localhost/php-
examples/filename.php.
8. The web application will be executed within the web browser.
PHP – Variables
• Variables are the entities that are used for storing the values.
• PHP is a dynamically typed language.
• Syntax: $variable_name = value;
• If the value is not assigned to the variable then they by default the value is
NULL.
• Rules for Variables:
– The variable must start with letter or underscore _.
– It consists of alphanumeric characters or underscore.
– There should not be space in the name of the variable.
– While assigning the values to the variable the variable must start with the $.
– Example: $marks = 100;
PHP – Data Types
• Four scalar data types used in PHP.
• Integer: To display the integer value. The size is 32 bits.
• Boolean: Only two types of values TRUE and FALSE.
• Double: To display the real values. It includes the number with decimal
point, exponentiation or both.
• String: The string literals can be defined using either single or double
quotes.
PHP – Constants
• Constant is an identifier that contains some value.
• Once the constant value is assigned to this identifier it does not get changed.
• The constant identifiers are specified in upper case.
• The valid constant name must start with letter or underscore.
• Use define function to assign value to the constant.
Example:
<?php
define(“MYVALUE”, “10”);
echo MYVALUE;
define(“1MYVALUE”, “something”);
echo 1MYVALUE;
?>
PHP – print Vs. echo
• print: Function used to create simple unformatted output.
Example:
print “Hello <b> World!!! </b>”
print (100);
<?php
print "<h2>PHP !</h2>";
print "Hello World!<br>";
?>
PHP – print Vs. echo
• echo: Simple statement that can be used with or without parenthesis.
Example:
echo “Hello <b> World!!! </b>”
$a – 10;
echo $a;
print in PHP echo in PHP
Print can only output one string Echo can output one or more strings
Print is slower than echo Echo is faster than print
Print always return 1 Echo does not return any value
PHP – Operators
Arithmetic Operators
Operator Name Example Explanation
+ Addition $a + $b Sum of operands
- Subtraction $a - $b Difference of operands
* Multiplication $a * $b Product of operands
/ Division $a / $b Quotient of operands
% Modulus $a % $b Remainder of operands
** Exponentiation $a ** $b $a raised to the power $b
PHP – Operators
Relational Operators
Operator Name Example Explanation
== Equal $a == $b Return TRUE if $a is equal to $b
=== Identical $a === $b
Return TRUE if $a is equal to $b, and they are of
same data type
!== Not identical $a !== $b
Return TRUE if $a is not equal to $b, and they are
not of same data type
!= Not equal $a != $b Return TRUE if $a is not equal to $b
<> Not equal $a <> $b Return TRUE if $a is not equal to $b
< Less than $a < $b Return TRUE if $a is less than $b
<= Less than or equal to $a <= $b Return TRUE if $a is less than or equal $b
>= Greater than or equal to $a >= $b Return TRUE if $a is greater than or equal $b
<=> Spaceship $a <=>$b
Return -1 if $a is less than $b
Return 0 if $a is equal $b
Return 1 if $a is greater than $b
PHP – Operators
Bitwise Operators
Operator Name Example Explanation
& And $a & $b
Bits that are 1 in both $a and $b are set
to 1, otherwise 0.
| Or (Inclusive or) $a | $b
Bits that are 1 in either $a or $b are set
to 1
^ Xor (Exclusive or) $a ^ $b
Bits that are 1 in either $a or $b are set
to 0.
~ Not ~$a
Bits that are 1 set to 0 and bits that are
0 are set to 1
<< Shift left $a << $b
Left shift the bits of operand $a $b
steps
>> Shift right $a >> $b
Right shift the bits of $a operand by $b
number of places
PHP – Operators
Incrementing/Decrementing Operators
Operator Name Example Explanation
++ Increment
++$a
Increment the value of $a by one, then
return $a
$a++
Return $a, then increment the value of
$a by one
-- decrement
--$a
Decrement the value of $a by one, then
return $a
$a--
Return $a, then decrement the value of
$a by one
PHP – Operators
Logical Operators
Operator Name Example Explanation
and AND $a and $b Return TRUE if both $a and $b are true
or OR $a or $b Return TRUE if either $a or $b is true
xor XOR $a xor $b
Return TRUE if either $ or $b is true
but not both
! NOT ! $a Return TRUE if $a is not true
&& AND $a && $b
Return TRUE if either $a and $b are
true
|| OR $a || $b Return TRUE if either $a or $b is true
PHP – Operators
Assignment Operators
Operator Name Example Explanation
= Assign $a = $b
The value of right operand is assigned
to the left operand.
+= Add then Assign $a += $b Addition same as $a = $a + $b
-= Subtract then Assign $a -= $b Subtraction same as $a = $a - $b
*=
Multiply then
Assign
$a *= $b Multiplication same as $a = $a * $b
/=
Divide then Assign
(quotient)
$a /= $b Find quotient same as $a = $a / $b
%=
Divide then Assign
(remainder)
$a %= $b Find remainder same as $a = $a % $b
PHP – Operators
String Operators
Operator Name Example Explanation
. Concatenation $a . $b Concatenate both $a and $b
.=
Concatenation and
Assignment
$a .= $b
First concatenate $a and $b, then assign
the concatenated string to $a, e.g. $a =
$a . $b
PHP – Operators
Array Operators
Operator Name Example Explanation
+ Union $a + $y Union of $a and $b
== Equality $a == $b
Return TRUE if $a and $b have same
key/value pair
!= Inequality $a != $b Return TRUE if $a is not equal to $b
=== Identity $a === $b
Return TRUE if $a and $b have same
key/value pair of same type in same
order
!== Non-Identity $a !== $b Return TRUE if $a is not identical to $b
<> Inequality $a <> $b Return TRUE if $a is not equal to $b
PHP – Flow Control and Looping
Statement Syntax
if-else
if (condition)
statement;
else
statement;
Switch…Case
switch(expression) {
case 1:statements
break;
case 2: statements
break;
….
default: statements
}
break: break;
continue: continue;
PHP – Flow Control and Looping
Statement Syntax
while
while(condition) {
statements;
}
do…while
do {
Statements;
} while(condition);
for
for(initialization; condition; increment){
Statements;
}
foreach Used to iterate through all the elements of array.
PHP – Arrays
• Array is a collection of similar type of elements, but in PHP you can have
the elements of mixed type together in single array.
• PHP array is an ordered map (contains value on the basis of key).
PHPArray Types
1. Indexed Array
2. Associative Array
3. Multidimensional Array
PHP – Arrays
Indexed Array:
PHP index is represented by number which starts from 0.
Use to store number, string and object in the PHP array.
All PHP array elements are assigned to an index number by default.
Example
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
PHP – Arrays
Indexed Array:
Example
<?php
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
PHP – Arrays
Associative Array
• Associative arrays are the arrays with named keys.
• It is a kind of array with name and value pair.
• Can associate name with each array elements in PHP using => symbol
Example:
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
(OR)
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
PHP – Arrays
Multidimensional Array
• PHP multidimensional array is
also known as array of arrays.
• It allows to store tabular data in
an array.
• PHP multidimensional array can
be represented in the form of
matrix which is represented by
row * column.
Example
<?php
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
for ($row = 0; $row < 3; $row++) {
for ($col = 0; $col < 3; $col++) {
echo $emp[$row][$col]." ";
}
echo "<br/>";
}
?>
PHP – Arrays
Function Purpose
extract($arr)
The array keys becomes the variable name and the array values
become the variable values
implode($arr) Converts array into string
explode(delimiter, str1,limit) Splits a string
array_flip($arr) Used to exchange the keys with their associated values in array
current($arr), next($arr) Traversing the array
sort(($arr) Sort arrays in ascending order
rsort($arr) Sort arrays in descending order
asort($arr) Sort associative arrays in ascending order, according to the value
ksort($arr) Sort associative arrays in ascending order, according to the key
array_change_key_case($arr,
CASE_CASENAME)
Changes the case of all key of an array
array_chunk(($arr, value) Splits array into chunks
array_reverse($arr) Returns an array containing elements in reversed order
count($arr) Counts all elements in an array
array_search(”target",$arr)
Searches the specified value in an array. It returns key if search is
successful.
PHP – Strings
• PHP string is a sequence of characters i.e., used to store and manipulate
text.
Example
<?php
$str1="Hello World";
$str2="Using double "quote" with backslash inside double quoted string";
$str3="Using escape sequences n in double quoted string";
echo "$str1 <br/> $str2 <br/> $str3";
?>
PHP – Strings
Function Purpose
strlen(str1) Used to return the length of a string.
strcmp(str1, str2) Compares the two strings
strtolower(str1) Converts the string to lower case
strtoupper(str1) Converts the string to upper case
trim(str1)
Remove whitespace or other characters from the beginning and end
of the string.
str_split(str1) Used to split a string into an array
strrev(str1) Used to reverse the string
substr( str1, start, length ) Return the part of a string
str_word_count(str1) Returns the number of words in the string
strpos(str1, str2) Searches for a specific text within a string
str_replace(str1, str2) Replaces some characters with some other characters in a string
PHP – Functions
• PHP function is a piece of code that can be reused many times.
• It can take input as argument list and return value.
Syntax:
function functionname(){
//code to be executed
}
PHP – File Handling
• PHP File System allows us to create file, read file line by line, read file
character by character, write file, append file, delete file and close file.
• Syntax:
<?php
$handle = fopen("c:folderfile.txt", "r"); //open file in read mode
$contents = fread($handle, filesize($filename)); //read file
$fp = fopen('data.txt', 'w’); //open file in write mode
fwrite($fp, 'hello ');
fwrite($fp, 'php file');
unlink('data.txt’); //delete file
fclose($handle);
?>
PHP – File Handling
• PHP Open File: fopen() function is used to open file or URL and returns
resource.
Mode Description
r Opens file in read-only mode. It places the file pointer at the beginning of the file.
r+ Opens file in read-write mode. It places the file pointer at the beginning of the file.
w
Opens file in write-only mode. It places the file pointer to the beginning of the file and
truncates the file to zero length. If file is not found, it creates a new file.
w+
Opens file in read-write mode. It places the file pointer to the beginning of the file and
truncates the file to zero length. If file is not found, it creates a new file.
a
Opens file in write-only mode. It places the file pointer to the end of the file. If file is not
found, it creates a new file.
a+
Opens file in read-write mode. It places the file pointer to the end of the file. If file is not
found, it creates a new file.
x
Creates and opens file in write-only mode. It places the file pointer at the beginning of the
file. If file is found, fopen() function returns FALSE.
x+ It is same as x but it creates and opens file in read-write mode.
c
Opens file in write-only mode. If the file does not exist, it is created. If it exists, it is neither
truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The
file pointer is positioned on the beginning of the file
c+ It is same as c but it opens file in read-write mode.
PHP – File Uploading
• PHP file upload features allows to upload binary and text files.
• One can have the full control over the file to be uploaded through PHP
authentication and file operation functions.
• move_uploaded_file(): Moves the uploaded file to a new location. The
move_uploaded_file() function checks internally if the file is uploaded thorough the
POST request. It moves the file if it is uploaded through the POST request.
$_FILES['filename']['name'] Returns file name
$_FILES['filename']['type'] Returns MIME type of the file
$_FILES['filename']['size'] Returns size of the file (in bytes)
$_FILES['filename']['tmp_name']
Returns temporary file name of the file which
was stored on the server.
$_FILES['filename']['error'] Returns error code associated with this file
PHP – Email Basics, Attachments
• PHP has mail()function which is useful in sending the mail from the script.
• Syntax:
mail (to, subject, message, headers, parameters)
Where,
to à Represents the address of receiver
subject à Specifies the subject of mail
message à Defines the message which is to be sent
header à This is optional and specifies the additional headers like Cc, Bcc
parameters à This is optional and specifies the additional parameters
Databases with PHP
<? Php
$servername = "localhost";
$username = "username";
$password = "password";
//code….
?>
Databases with PHP
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
mysqli_close($conn);
Databases with PHP
// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
Databases with PHP
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
Databases with PHP
// Insert Query
$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);
}
Databases with PHP
// Select Query
$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";
}
Databases with PHP
// Select Query
$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE lastname='Doe'";
$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";
}
Databases with PHP
// Select Query
$sql = "SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname";
$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";
}
Databases with PHP
// 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);
}
Databases with PHP
// sql to update a record
$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);
}

More Related Content

Similar to IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf

Similar to IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf (20)

Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
Php Basic
Php BasicPhp Basic
Php Basic
 
MIND sweeping introduction to PHP
MIND sweeping introduction to PHPMIND sweeping introduction to PHP
MIND sweeping introduction to PHP
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
 
Php basics
Php basicsPhp basics
Php basics
 
05php
05php05php
05php
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
P H P Part I, By Kian
P H P  Part  I,  By  KianP H P  Part  I,  By  Kian
P H P Part I, By Kian
 
05php
05php05php
05php
 
WT_PHP_PART1.pdf
WT_PHP_PART1.pdfWT_PHP_PART1.pdf
WT_PHP_PART1.pdf
 
php fundamental
php fundamentalphp fundamental
php fundamental
 
Php introduction with history of php
Php introduction with history of phpPhp introduction with history of php
Php introduction with history of php
 
php
phpphp
php
 
Php using variables-operators
Php using variables-operatorsPhp using variables-operators
Php using variables-operators
 
Php introduction
Php introductionPhp introduction
Php introduction
 
Php
PhpPhp
Php
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
rtwerewr
rtwerewrrtwerewr
rtwerewr
 

More from pkaviya

IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivitypkaviya
 
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and ScriptingIT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and Scriptingpkaviya
 
IT2255 Web Essentials - Unit II Web Designing
IT2255 Web Essentials - Unit II  Web DesigningIT2255 Web Essentials - Unit II  Web Designing
IT2255 Web Essentials - Unit II Web Designingpkaviya
 
IT2255 Web Essentials - Unit I Website Basics
IT2255 Web Essentials - Unit I  Website BasicsIT2255 Web Essentials - Unit I  Website Basics
IT2255 Web Essentials - Unit I Website Basicspkaviya
 
BT2252 - ETBT - UNIT 3 - Enzyme Immobilization.pdf
BT2252 - ETBT - UNIT 3 - Enzyme Immobilization.pdfBT2252 - ETBT - UNIT 3 - Enzyme Immobilization.pdf
BT2252 - ETBT - UNIT 3 - Enzyme Immobilization.pdfpkaviya
 
OIT552 Cloud Computing Material
OIT552 Cloud Computing MaterialOIT552 Cloud Computing Material
OIT552 Cloud Computing Materialpkaviya
 
OIT552 Cloud Computing - Question Bank
OIT552 Cloud Computing - Question BankOIT552 Cloud Computing - Question Bank
OIT552 Cloud Computing - Question Bankpkaviya
 
CS8791 Cloud Computing - Question Bank
CS8791 Cloud Computing - Question BankCS8791 Cloud Computing - Question Bank
CS8791 Cloud Computing - Question Bankpkaviya
 
CS8592 Object Oriented Analysis & Design - UNIT V
CS8592 Object Oriented Analysis & Design - UNIT V CS8592 Object Oriented Analysis & Design - UNIT V
CS8592 Object Oriented Analysis & Design - UNIT V pkaviya
 
CS8592 Object Oriented Analysis & Design - UNIT IV
CS8592 Object Oriented Analysis & Design - UNIT IV CS8592 Object Oriented Analysis & Design - UNIT IV
CS8592 Object Oriented Analysis & Design - UNIT IV pkaviya
 
CS8592 Object Oriented Analysis & Design - UNIT III
CS8592 Object Oriented Analysis & Design - UNIT III CS8592 Object Oriented Analysis & Design - UNIT III
CS8592 Object Oriented Analysis & Design - UNIT III pkaviya
 
CS8592 Object Oriented Analysis & Design - UNIT II
CS8592 Object Oriented Analysis & Design - UNIT IICS8592 Object Oriented Analysis & Design - UNIT II
CS8592 Object Oriented Analysis & Design - UNIT IIpkaviya
 
CS8592 Object Oriented Analysis & Design - UNIT I
CS8592 Object Oriented Analysis & Design - UNIT ICS8592 Object Oriented Analysis & Design - UNIT I
CS8592 Object Oriented Analysis & Design - UNIT Ipkaviya
 
Cs8591 Computer Networks - UNIT V
Cs8591 Computer Networks - UNIT VCs8591 Computer Networks - UNIT V
Cs8591 Computer Networks - UNIT Vpkaviya
 
CS8591 Computer Networks - Unit IV
CS8591 Computer Networks - Unit IVCS8591 Computer Networks - Unit IV
CS8591 Computer Networks - Unit IVpkaviya
 
CS8591 Computer Networks - Unit III
CS8591 Computer Networks - Unit IIICS8591 Computer Networks - Unit III
CS8591 Computer Networks - Unit IIIpkaviya
 
CS8591 Computer Networks - Unit II
CS8591 Computer Networks - Unit II CS8591 Computer Networks - Unit II
CS8591 Computer Networks - Unit II pkaviya
 
CS8591 Computer Networks - Unit I
CS8591 Computer Networks - Unit ICS8591 Computer Networks - Unit I
CS8591 Computer Networks - Unit Ipkaviya
 
IT8602 Mobile Communication - Unit V
IT8602 Mobile Communication - Unit V IT8602 Mobile Communication - Unit V
IT8602 Mobile Communication - Unit V pkaviya
 
IT8602 - Mobile Communication Unit IV
IT8602 - Mobile Communication   Unit IV IT8602 - Mobile Communication   Unit IV
IT8602 - Mobile Communication Unit IV pkaviya
 

More from pkaviya (20)

IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
 
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and ScriptingIT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
 
IT2255 Web Essentials - Unit II Web Designing
IT2255 Web Essentials - Unit II  Web DesigningIT2255 Web Essentials - Unit II  Web Designing
IT2255 Web Essentials - Unit II Web Designing
 
IT2255 Web Essentials - Unit I Website Basics
IT2255 Web Essentials - Unit I  Website BasicsIT2255 Web Essentials - Unit I  Website Basics
IT2255 Web Essentials - Unit I Website Basics
 
BT2252 - ETBT - UNIT 3 - Enzyme Immobilization.pdf
BT2252 - ETBT - UNIT 3 - Enzyme Immobilization.pdfBT2252 - ETBT - UNIT 3 - Enzyme Immobilization.pdf
BT2252 - ETBT - UNIT 3 - Enzyme Immobilization.pdf
 
OIT552 Cloud Computing Material
OIT552 Cloud Computing MaterialOIT552 Cloud Computing Material
OIT552 Cloud Computing Material
 
OIT552 Cloud Computing - Question Bank
OIT552 Cloud Computing - Question BankOIT552 Cloud Computing - Question Bank
OIT552 Cloud Computing - Question Bank
 
CS8791 Cloud Computing - Question Bank
CS8791 Cloud Computing - Question BankCS8791 Cloud Computing - Question Bank
CS8791 Cloud Computing - Question Bank
 
CS8592 Object Oriented Analysis & Design - UNIT V
CS8592 Object Oriented Analysis & Design - UNIT V CS8592 Object Oriented Analysis & Design - UNIT V
CS8592 Object Oriented Analysis & Design - UNIT V
 
CS8592 Object Oriented Analysis & Design - UNIT IV
CS8592 Object Oriented Analysis & Design - UNIT IV CS8592 Object Oriented Analysis & Design - UNIT IV
CS8592 Object Oriented Analysis & Design - UNIT IV
 
CS8592 Object Oriented Analysis & Design - UNIT III
CS8592 Object Oriented Analysis & Design - UNIT III CS8592 Object Oriented Analysis & Design - UNIT III
CS8592 Object Oriented Analysis & Design - UNIT III
 
CS8592 Object Oriented Analysis & Design - UNIT II
CS8592 Object Oriented Analysis & Design - UNIT IICS8592 Object Oriented Analysis & Design - UNIT II
CS8592 Object Oriented Analysis & Design - UNIT II
 
CS8592 Object Oriented Analysis & Design - UNIT I
CS8592 Object Oriented Analysis & Design - UNIT ICS8592 Object Oriented Analysis & Design - UNIT I
CS8592 Object Oriented Analysis & Design - UNIT I
 
Cs8591 Computer Networks - UNIT V
Cs8591 Computer Networks - UNIT VCs8591 Computer Networks - UNIT V
Cs8591 Computer Networks - UNIT V
 
CS8591 Computer Networks - Unit IV
CS8591 Computer Networks - Unit IVCS8591 Computer Networks - Unit IV
CS8591 Computer Networks - Unit IV
 
CS8591 Computer Networks - Unit III
CS8591 Computer Networks - Unit IIICS8591 Computer Networks - Unit III
CS8591 Computer Networks - Unit III
 
CS8591 Computer Networks - Unit II
CS8591 Computer Networks - Unit II CS8591 Computer Networks - Unit II
CS8591 Computer Networks - Unit II
 
CS8591 Computer Networks - Unit I
CS8591 Computer Networks - Unit ICS8591 Computer Networks - Unit I
CS8591 Computer Networks - Unit I
 
IT8602 Mobile Communication - Unit V
IT8602 Mobile Communication - Unit V IT8602 Mobile Communication - Unit V
IT8602 Mobile Communication - Unit V
 
IT8602 - Mobile Communication Unit IV
IT8602 - Mobile Communication   Unit IV IT8602 - Mobile Communication   Unit IV
IT8602 - Mobile Communication Unit IV
 

Recently uploaded

THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 

Recently uploaded (20)

THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 

IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf

  • 1. IT2253 Web Essentials Unit IV – Server-Side Processing and Scripting-PHP Kaviya.P Kamaraj College of Engineering & Technology
  • 2. Unit IV – Server-Side Processing and Scripting-PHP PHP – Working principle of PHP – PHP Variables – Constants – Operators – Flow Control and Looping – Arrays – Strings – Functions – File Handling – File Uploading – Email Basics – Email with attachments – PHP and HTML – Simple PHP scripts – Databases with PHP.
  • 3. PHP – Introduction • Developed in 1994 by Apache Group. • PHP: Hypertext Preprocessor. • A server scripting language. • Mainly used for form handling and database access. • A powerful tool for making dynamic and interactive webpages.
  • 4. PHP – Introduction Advantages • Very simple and easy to learn • Interpreted Language • Open source • Platform Independent • Can directly integrated with HTML • Support to design dynamic web applications • Reliable, efficient and flexible scripting language • Provides support for file system, managing user sessions, cookies, E-mail Management, execute the system commands, create directories, etc.,
  • 5. PHP – Introduction Syntax The code must be enclosed with in: <?php // Statements (or) Codes ?> • If anyone wants to refer file then “inlude” construct is used. Example: Include(“myfile.html”) Comments // 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 */
  • 6. Working Principle of PHP • The most popular way of installing PHP is using XAMPP. • XAMPP is a free distribution package that makes it easy to install Apache Web Server, MySQL, PHP, PEAR. 1. Go to the site: https://www.apachefriends.org/index.html 2. Click on download XAMPP for Windows or Linux depending on the OS 3. When prompted for the download, click “Save” and wait for the download finish. 4. Install the program and click on “Run”. Accept default settings by clicking “Next” button. Finally, installation completion message is displayed. 5. On the drive, the XAMPP folder will be created. Click on xampp_start file, this will enable to start Apache, MySQL and Tomcat start.
  • 7. Working Principle of PHP 6. The control panel for XAMPP will look like this, 6. Write a PHP script and save it in C:XAMPPhtdocsphp-examples folder by giving the filename and extension as .php. 7. Open the web browser and type http://localhost/php- examples/filename.php. 8. The web application will be executed within the web browser.
  • 8. PHP – Variables • Variables are the entities that are used for storing the values. • PHP is a dynamically typed language. • Syntax: $variable_name = value; • If the value is not assigned to the variable then they by default the value is NULL. • Rules for Variables: – The variable must start with letter or underscore _. – It consists of alphanumeric characters or underscore. – There should not be space in the name of the variable. – While assigning the values to the variable the variable must start with the $. – Example: $marks = 100;
  • 9. PHP – Data Types • Four scalar data types used in PHP. • Integer: To display the integer value. The size is 32 bits. • Boolean: Only two types of values TRUE and FALSE. • Double: To display the real values. It includes the number with decimal point, exponentiation or both. • String: The string literals can be defined using either single or double quotes.
  • 10. PHP – Constants • Constant is an identifier that contains some value. • Once the constant value is assigned to this identifier it does not get changed. • The constant identifiers are specified in upper case. • The valid constant name must start with letter or underscore. • Use define function to assign value to the constant. Example: <?php define(“MYVALUE”, “10”); echo MYVALUE; define(“1MYVALUE”, “something”); echo 1MYVALUE; ?>
  • 11. PHP – print Vs. echo • print: Function used to create simple unformatted output. Example: print “Hello <b> World!!! </b>” print (100); <?php print "<h2>PHP !</h2>"; print "Hello World!<br>"; ?>
  • 12. PHP – print Vs. echo • echo: Simple statement that can be used with or without parenthesis. Example: echo “Hello <b> World!!! </b>” $a – 10; echo $a; print in PHP echo in PHP Print can only output one string Echo can output one or more strings Print is slower than echo Echo is faster than print Print always return 1 Echo does not return any value
  • 13. PHP – Operators Arithmetic Operators Operator Name Example Explanation + Addition $a + $b Sum of operands - Subtraction $a - $b Difference of operands * Multiplication $a * $b Product of operands / Division $a / $b Quotient of operands % Modulus $a % $b Remainder of operands ** Exponentiation $a ** $b $a raised to the power $b
  • 14. PHP – Operators Relational Operators Operator Name Example Explanation == Equal $a == $b Return TRUE if $a is equal to $b === Identical $a === $b Return TRUE if $a is equal to $b, and they are of same data type !== Not identical $a !== $b Return TRUE if $a is not equal to $b, and they are not of same data type != Not equal $a != $b Return TRUE if $a is not equal to $b <> Not equal $a <> $b Return TRUE if $a is not equal to $b < Less than $a < $b Return TRUE if $a is less than $b <= Less than or equal to $a <= $b Return TRUE if $a is less than or equal $b >= Greater than or equal to $a >= $b Return TRUE if $a is greater than or equal $b <=> Spaceship $a <=>$b Return -1 if $a is less than $b Return 0 if $a is equal $b Return 1 if $a is greater than $b
  • 15. PHP – Operators Bitwise Operators Operator Name Example Explanation & And $a & $b Bits that are 1 in both $a and $b are set to 1, otherwise 0. | Or (Inclusive or) $a | $b Bits that are 1 in either $a or $b are set to 1 ^ Xor (Exclusive or) $a ^ $b Bits that are 1 in either $a or $b are set to 0. ~ Not ~$a Bits that are 1 set to 0 and bits that are 0 are set to 1 << Shift left $a << $b Left shift the bits of operand $a $b steps >> Shift right $a >> $b Right shift the bits of $a operand by $b number of places
  • 16. PHP – Operators Incrementing/Decrementing Operators Operator Name Example Explanation ++ Increment ++$a Increment the value of $a by one, then return $a $a++ Return $a, then increment the value of $a by one -- decrement --$a Decrement the value of $a by one, then return $a $a-- Return $a, then decrement the value of $a by one
  • 17. PHP – Operators Logical Operators Operator Name Example Explanation and AND $a and $b Return TRUE if both $a and $b are true or OR $a or $b Return TRUE if either $a or $b is true xor XOR $a xor $b Return TRUE if either $ or $b is true but not both ! NOT ! $a Return TRUE if $a is not true && AND $a && $b Return TRUE if either $a and $b are true || OR $a || $b Return TRUE if either $a or $b is true
  • 18. PHP – Operators Assignment Operators Operator Name Example Explanation = Assign $a = $b The value of right operand is assigned to the left operand. += Add then Assign $a += $b Addition same as $a = $a + $b -= Subtract then Assign $a -= $b Subtraction same as $a = $a - $b *= Multiply then Assign $a *= $b Multiplication same as $a = $a * $b /= Divide then Assign (quotient) $a /= $b Find quotient same as $a = $a / $b %= Divide then Assign (remainder) $a %= $b Find remainder same as $a = $a % $b
  • 19. PHP – Operators String Operators Operator Name Example Explanation . Concatenation $a . $b Concatenate both $a and $b .= Concatenation and Assignment $a .= $b First concatenate $a and $b, then assign the concatenated string to $a, e.g. $a = $a . $b
  • 20. PHP – Operators Array Operators Operator Name Example Explanation + Union $a + $y Union of $a and $b == Equality $a == $b Return TRUE if $a and $b have same key/value pair != Inequality $a != $b Return TRUE if $a is not equal to $b === Identity $a === $b Return TRUE if $a and $b have same key/value pair of same type in same order !== Non-Identity $a !== $b Return TRUE if $a is not identical to $b <> Inequality $a <> $b Return TRUE if $a is not equal to $b
  • 21. PHP – Flow Control and Looping Statement Syntax if-else if (condition) statement; else statement; Switch…Case switch(expression) { case 1:statements break; case 2: statements break; …. default: statements } break: break; continue: continue;
  • 22. PHP – Flow Control and Looping Statement Syntax while while(condition) { statements; } do…while do { Statements; } while(condition); for for(initialization; condition; increment){ Statements; } foreach Used to iterate through all the elements of array.
  • 23. PHP – Arrays • Array is a collection of similar type of elements, but in PHP you can have the elements of mixed type together in single array. • PHP array is an ordered map (contains value on the basis of key). PHPArray Types 1. Indexed Array 2. Associative Array 3. Multidimensional Array
  • 24. PHP – Arrays Indexed Array: PHP index is represented by number which starts from 0. Use to store number, string and object in the PHP array. All PHP array elements are assigned to an index number by default. Example <?php $season=array("summer","winter","spring","autumn"); echo "Season are: $season[0], $season[1], $season[2] and $season[3]"; ?>
  • 25. PHP – Arrays Indexed Array: Example <?php $season[0]="summer"; $season[1]="winter"; $season[2]="spring"; $season[3]="autumn"; echo "Season are: $season[0], $season[1], $season[2] and $season[3]"; ?>
  • 26. PHP – Arrays Associative Array • Associative arrays are the arrays with named keys. • It is a kind of array with name and value pair. • Can associate name with each array elements in PHP using => symbol Example: $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000"); (OR) $salary["Sonoo"]="350000"; $salary["John"]="450000"; $salary["Kartik"]="200000";
  • 27. PHP – Arrays Multidimensional Array • PHP multidimensional array is also known as array of arrays. • It allows to store tabular data in an array. • PHP multidimensional array can be represented in the form of matrix which is represented by row * column. Example <?php $emp = array ( array(1,"sonoo",400000), array(2,"john",500000), array(3,"rahul",300000) ); for ($row = 0; $row < 3; $row++) { for ($col = 0; $col < 3; $col++) { echo $emp[$row][$col]." "; } echo "<br/>"; } ?>
  • 28. PHP – Arrays Function Purpose extract($arr) The array keys becomes the variable name and the array values become the variable values implode($arr) Converts array into string explode(delimiter, str1,limit) Splits a string array_flip($arr) Used to exchange the keys with their associated values in array current($arr), next($arr) Traversing the array sort(($arr) Sort arrays in ascending order rsort($arr) Sort arrays in descending order asort($arr) Sort associative arrays in ascending order, according to the value ksort($arr) Sort associative arrays in ascending order, according to the key array_change_key_case($arr, CASE_CASENAME) Changes the case of all key of an array array_chunk(($arr, value) Splits array into chunks array_reverse($arr) Returns an array containing elements in reversed order count($arr) Counts all elements in an array array_search(”target",$arr) Searches the specified value in an array. It returns key if search is successful.
  • 29. PHP – Strings • PHP string is a sequence of characters i.e., used to store and manipulate text. Example <?php $str1="Hello World"; $str2="Using double "quote" with backslash inside double quoted string"; $str3="Using escape sequences n in double quoted string"; echo "$str1 <br/> $str2 <br/> $str3"; ?>
  • 30. PHP – Strings Function Purpose strlen(str1) Used to return the length of a string. strcmp(str1, str2) Compares the two strings strtolower(str1) Converts the string to lower case strtoupper(str1) Converts the string to upper case trim(str1) Remove whitespace or other characters from the beginning and end of the string. str_split(str1) Used to split a string into an array strrev(str1) Used to reverse the string substr( str1, start, length ) Return the part of a string str_word_count(str1) Returns the number of words in the string strpos(str1, str2) Searches for a specific text within a string str_replace(str1, str2) Replaces some characters with some other characters in a string
  • 31. PHP – Functions • PHP function is a piece of code that can be reused many times. • It can take input as argument list and return value. Syntax: function functionname(){ //code to be executed }
  • 32. PHP – File Handling • PHP File System allows us to create file, read file line by line, read file character by character, write file, append file, delete file and close file. • Syntax: <?php $handle = fopen("c:folderfile.txt", "r"); //open file in read mode $contents = fread($handle, filesize($filename)); //read file $fp = fopen('data.txt', 'w’); //open file in write mode fwrite($fp, 'hello '); fwrite($fp, 'php file'); unlink('data.txt’); //delete file fclose($handle); ?>
  • 33. PHP – File Handling • PHP Open File: fopen() function is used to open file or URL and returns resource. Mode Description r Opens file in read-only mode. It places the file pointer at the beginning of the file. r+ Opens file in read-write mode. It places the file pointer at the beginning of the file. w Opens file in write-only mode. It places the file pointer to the beginning of the file and truncates the file to zero length. If file is not found, it creates a new file. w+ Opens file in read-write mode. It places the file pointer to the beginning of the file and truncates the file to zero length. If file is not found, it creates a new file. a Opens file in write-only mode. It places the file pointer to the end of the file. If file is not found, it creates a new file. a+ Opens file in read-write mode. It places the file pointer to the end of the file. If file is not found, it creates a new file. x Creates and opens file in write-only mode. It places the file pointer at the beginning of the file. If file is found, fopen() function returns FALSE. x+ It is same as x but it creates and opens file in read-write mode. c Opens file in write-only mode. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file c+ It is same as c but it opens file in read-write mode.
  • 34. PHP – File Uploading • PHP file upload features allows to upload binary and text files. • One can have the full control over the file to be uploaded through PHP authentication and file operation functions. • move_uploaded_file(): Moves the uploaded file to a new location. The move_uploaded_file() function checks internally if the file is uploaded thorough the POST request. It moves the file if it is uploaded through the POST request. $_FILES['filename']['name'] Returns file name $_FILES['filename']['type'] Returns MIME type of the file $_FILES['filename']['size'] Returns size of the file (in bytes) $_FILES['filename']['tmp_name'] Returns temporary file name of the file which was stored on the server. $_FILES['filename']['error'] Returns error code associated with this file
  • 35. PHP – Email Basics, Attachments • PHP has mail()function which is useful in sending the mail from the script. • Syntax: mail (to, subject, message, headers, parameters) Where, to à Represents the address of receiver subject à Specifies the subject of mail message à Defines the message which is to be sent header à This is optional and specifies the additional headers like Cc, Bcc parameters à This is optional and specifies the additional parameters
  • 36. Databases with PHP <? Php $servername = "localhost"; $username = "username"; $password = "password"; //code…. ?>
  • 37. Databases with PHP // Create connection $conn = mysqli_connect($servername, $username, $password); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully"; mysqli_close($conn);
  • 38. Databases with PHP // Create database $sql = "CREATE DATABASE myDB"; if (mysqli_query($conn, $sql)) { echo "Database created successfully"; } else { echo "Error creating database: " . mysqli_error($conn); }
  • 39. Databases with PHP // sql to create table $sql = "CREATE TABLE MyGuests ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )"; if (mysqli_query($conn, $sql)) { echo "Table MyGuests created successfully"; } else { echo "Error creating table: " . mysqli_error($conn); }
  • 40. Databases with PHP // Insert Query $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); }
  • 41. Databases with PHP // Select Query $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"; }
  • 42. Databases with PHP // Select Query $sql = "SELECT id, firstname, lastname FROM MyGuests WHERE lastname='Doe'"; $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"; }
  • 43. Databases with PHP // Select Query $sql = "SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname"; $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"; }
  • 44. Databases with PHP // 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); }
  • 45. Databases with PHP // sql to update a record $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); }