0% found this document useful (0 votes)
8 views

Php Noteees

The document provides an overview of PHP, including its history, advantages, syntax, variables, data types, expressions, control statements, and operators. It highlights PHP as an open-source, server-side scripting language suitable for web development, emphasizing its ease of use, flexibility, and strong community support. Additionally, it covers the fundamental concepts necessary for understanding and utilizing PHP in web application development.

Uploaded by

tejasnarwade.eng
Copyright
© © All Rights Reserved
Available Formats
Download as ODG, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Php Noteees

The document provides an overview of PHP, including its history, advantages, syntax, variables, data types, expressions, control statements, and operators. It highlights PHP as an open-source, server-side scripting language suitable for web development, emphasizing its ease of use, flexibility, and strong community support. Additionally, it covers the fundamental concepts necessary for understanding and utilizing PHP in web application development.

Uploaded by

tejasnarwade.eng
Copyright
© © All Rights Reserved
Available Formats
Download as ODG, PDF, TXT or read online on Scribd
You are on page 1/ 118

Mrs.

Poonam Amit Kamble Web based Application Development with PHP(22619)

1.1  History
 Advantages Of PHP
 Syntax of PHP
1.2  Variables
 Data Types
 Expressions
 Operators
 Constants
1.3 Decision Making Control Statements :
 if
 if-else
 nested if
 switch
 break
 continue
1.4 Loop Control Structures :
 while
 do-while
 for
 foreach

Unit I
Expressions and Control Statements in PHP Page 1
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

1.1 Introduction to PHP :

PHP, an acronym for Hypertext Preprocessor, is a widely-used open source


general-purpose scripting language. It is a cross-platform, HTML-embedded
server-side scripting language and is especially suited for web development.

Where

 Server-side means that PHP scripts execute on the Web server, not
within the browser on your local machine.
 Cross-platform means that PHP scripts can run on many different
operating systems and Web servers. PHP is available for the two
most popular Web server configurations IIS and Apache.
 HTML embedded scripting language means that PHP statements and
commands are actually embedded in your HTML documents.

(i)
History of PHP :

1) PHP was developed by Rasmus Lerdorf in 1994. Early non-released


versions were used on his home page to keep track of who was
looking at his online resume.
2) The first version used by others was available sometime in early 1995
and was known as the Personal Home Page Tools.
3) In mid-1995 he extended them to work with web forms and to
communicate with databases, and called this implementation
"Personal Home Page/Forms Interpreter" or PHP/FI.
4) Zeev Suraski and Andi Gutmans rewrote the parser in 1997 and
formed the base of PHP 3, changing the language's name to
the recursive acronym PHP: Hypertext Preprocessor.
5) Latest version of PHP is 8.2 which was released on 8 December 2022
and it will be supported till 8 december 2025.

Unit I
Expressions and Control Statements in PHP Page 2
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

(ii) Advantages of PHP :


Some of the most important advantages of PHP are as following :

1. Open Source and Free of Cost:

One of the most vital advantages of PHP is that it is accessible to all.


People can download it from an open-source and get it for free. One
can download it anywhere and readily use it for web application
development.

2. Platform Independence:

Another important factor is that since PHP-based applications can run


on any OS such as UNIX, Windows, Linux, etc., people can use it
without worrying about a platform where one can use it.

3. Easy loading:

One can load the PHP-based applications easily and connect them to a
database. People mainly use it since it has a fast rate of loading even if
it is over a slow internet connection and speed than other
programming languages.

4. User-friendly:

It has a less learning curve, and one can learn it quickly. The language
is straightforward to use, and if one knows about C programming, they
can catch on to PHP language quickly for application development.

5. Stable:

Unlike other scripting languages, PHP is very stable over the years
and can provide one with assistance and continuous support. They can
get help over various versions as well.

6. No lengthy code required:

As we mentioned earlier, it is a simple language that people can utilize


for various purposes. It has such a quality that one can use it without
having to write lengthy codes and sophisticated structures for any web
application event.

Unit I
Expressions and Control Statements in PHP Page 3
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

7. Flexible:

It is highly flexible, and people can readily use it to combine its


function with various other programming languages. They can use the
software packages as the foremost effective technology for every
feature.

8. Increased Job opportunity:

Since PHP is very popular, many developers and developing


communities have evolved who have knowledge of this language.
People who know the simple language can become potential
candidates for jobs.

9. Database connection:

It has a built-in database connection that helps to connect databases


and reduce the trouble and the time to develop web applications or
content-based sites altogether.

10. Library support:

PHP has strong library support using which one can utilize the various
function modules for data representation.

(iii) Syntax of PHP :


There are four different pairs of opening and closing tags which can be used
in php. Here is the list of tags.

a) Default syntax
b) Short open Tags
c) Omit the PHP closing tag at the end of the file.

Unit I
Expressions and Control Statements in PHP Page 4
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

a) Default Syntax

The default syntax starts with "<? php" and ends with "?>".

Example:

<?php

echo "Default Syntax";

?>

b) Short open Tags

The short tags starts with "<?" and ends with "?>". Short style tags are only
available when they are enabled in php.ini configuration file on servers.

Example:

<?

echo "PHP example with short-tags";

?>

c) Omit the PHP closing tag at the end of the file :

It is recommended that a closing PHP tag shall be omitted in a file


containing only PHP code so that occurrences of accidental whitespace or
new lines being added after the PHP closing tag, which may start output
buffering causing uncalled for effects can be avoided.

Example:

<?php

echo "PHP example with short-tags";

Unit I
Expressions and Control Statements in PHP Page 5
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

1.2 (i) Variables in PHP :

The syntax for PHP variables is similar to C and most other programming
languages. There are
three primary differences:
1. Variable names must be preceded by a dollar sign ($).
2. Variables do not need to be declared before being used.
3. Variables are dynamically typed, so you do not need to specify the type
(e.g., char, int, float, etc.).

Rules for Naming Variables :

A variable can have a short name, like x, or a more descriptive name, like
carName. The rules for PHP variable names:
• Variables in PHP starts with a $ sign, followed by the name of the variable
• The variable name must begin with a letter or the underscore character
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• A variable name should not contain spaces
• Variable names are case sensitive (y and Y are two different variables).

Example :-
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>

output :
9

Variable Variables
You can reference the value of a variable whose name is stored in another
variable.
For example:
$foo = 'bar';
$$foo = 'baz';
After the second statement executes, the variable $bar has the value "baz".

Unit I
Expressions and Control Statements in PHP Page 6
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

Variable References
In PHP, references are how you create variable alternatives. To make $black
an another name for the variable $white, use:
$black =& $white;
The old value of $black is lost.

Scope of Variable

PHP has three different variable scopes:


1) Local
2) global
3) static

1) Local Scope :
 A variable declared within a PHP function is local and can only be
accessed within that function. (the variable has local scope):

<?php
$a = 5; // global scope
function myTest()
{
echo $a; // local scope
}
myTest();
?>

 The script above will not produce any output because the echo
statement refers to the local scope variable $a, which has not been
assigned a value within this scope.
 You can have local variables with the same name in different
functions, because local variables are only recognized by the function
in which they are declared.
 Local variables are deleted as soon as the function is completed.

2) Global Scope :
 Global scope refers to any variable that is defined outside of any
function. Global variables can be accessed from any part of the script
that is not inside a function. To access a global variable from within a
function, use the global keyword:

Unit I
Expressions and Control Statements in PHP Page 7
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

<?php
$a = 5;
$b = 10;
function myTest()
{
global $a, $b;
$b = $a + $b;
}
myTest();
echo $b;
?>

Output:
15

3) Static Scope :
 When a function is completed, all of its variables are normally
deleted. However, sometimes you want a local variable to not be
deleted.
 To do this, use the static keyword when you first declare the
variable:
<? php
function add()
{
static $a=10;
$b=20;
$a++;
$b++;
echo $a;
echo "<br>";
echo $b;
echo "<br>";
}
add();
add();
?>

Output :
11
21
12
21

Unit I
Expressions and Control Statements in PHP Page 8
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 Then, each time the function is called, that variable will still have
the information it contained from the last time the function was
called.
 The variable is still local to the function.

(ii) Data Types in PHP :

The main data types used to construct variables are:


 Integers - whole numbers like 23, 1254, 964 etc.
Example:
<?php
$x = 55;
var_dump($x);
?>

Output-
int(55)

 Float - floating-point numbers like 46.2, 733.21 etc


Example:
<?php
$x = 15.36;
var_dump($x);
?>

Output-
float(15.36)

 Booleans - only two possible values, true or false.


<?php
$x = true;
$y = false;
Var_dump($x);
Var_dump($y);
?>

Output-
bool(true)
bool(false)
Unit I
Expressions and Control Statements in PHP Page 9
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 Strings - set of characters, like Welcome to PHP Programming.


Example:
<?php
$x = "Hello world!";
var_dump($x);
?>

Output-
string(12)

 Arrays - named and indexed collections of other values


Example-
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>

Output
array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}

 Objects - instances of predefined classes


Example-
<?php
class fruits {
function mango() {
$desc = "Mango is king of fruits...";
echo $desc.”<br>”;
}
}
$obj = new fruits();
$obj -> mango();
Var_dump($obj);
?>

Unit I
Expressions and Control Statements in PHP Page 10
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

Output –
Mango is king of fruits...
object(fruits)#1 (0) { }

<?php
class fruits {
function mango() {
$weight=50;
$desc = "Mango is king of fruits...";
$this->weight=$weight;
echo $desc."It has weight ".$weight." gms.";
echo "<br>";
}
}
$obj = new fruits($weight);
$obj->mango();
var_dump($obj);
?>

Output :
Mango is king of fruits...It has weight 50 gms.
object(fruits)#1 (1) { ["weight"]=> int(50) }

 Null - special data type which can have only one value i.e. NULL.
Example:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>

Output –
NULL

 Resource – It is not an actual data type. It is the storing of a


reference to functions and resources external to PHP e.g. Database
call.

Unit I
Expressions and Control Statements in PHP Page 11
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

(iii) Expressions and Operators :

Expressions :

Using variables within expressions to do something is what PHP is all


about. The statement which gives value is called statements.
<?php
$name = „Rob‟; Expression
echo $name;
?>

Operators :
Operators are used to perform operations on variables and values. PHP
divides the operators in the following groups:

1) Arithmetic operators
2) Assignment operators
3) Comparison operators
4) Increment/Decrement operators
5) Logical operators
6) String operators
7) Array operators

1) Arithmetic operators :

Operator Name Example Result

+ Addition $x + $y Sum of $x and $y

- Subtraction $x - $y Difference of $x and $y

* Multiplication $x * $y Product of $x and $y

/ Division $x / $y Quotient of $x and $y

Unit I
Expressions and Control Statements in PHP Page 12
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

% Modulus $x % $y Remainder of $x divided by $y

** Exponentiation $x ** $y Result of raising $x to the $y'th power

2) Assignment operators :

Assignment Same as... Description

x=y x=y The left operand gets set to the value


of the expression on the right

x += y x=x+y Addition

x -= y x=x-y Subtraction

x *= y x=x*y Multiplication

x /= y x=x/y Division

x %= y x=x%y Modulus

3) String Operator :

Unit I
Expressions and Control Statements in PHP Page 13
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

4) Increment/ Decrement Operators:

5) Logical Operators:

Unit I
Expressions and Control Statements in PHP Page 14
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

6) Comparision Operators :

7) Array Operators :

Unit I
Expressions and Control Statements in PHP Page 15
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

(iv) Constants in PHP :

 Constants are like variables except that once they are defined they
cannot be changed or undefined.
 A constant is an identifier (name) for a simple value. The value
cannot be changed during the script.
 A valid constant name starts with a letter or underscore (no $ sign
before the constant name).
 Note: Unlike variables, constants are automatically global across the
entire script.
 To create a constant, use the define() function.
Syntax
define(name, value, case-insensitive)

Parameters:
 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. Default is false.

Example :

Program-1(case insensitive is false)


<?php
define("GREETING", "Welcome to PHP Programming…");
echo GREETING;
?>
Output :
Welcome to PHP Programming…

Program-2(case insensitive is true)


<?php
define("Greeting", "Welcome to PHP Programming…",true);
echo GREETING;
?>
Output :
Welcome to PHP Programming…

Unit I
Expressions and Control Statements in PHP Page 16
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

1.3 Decision making Control Statements :-


Decision making or flow control is the process of determining the order in
which statements execute in a program.

 PHP If Else
PHP if else statement is used to test condition. There are various ways to use
if statement in PHP.
1) if
2) if-else
3) if-else-if
4) nested if

(i)
PHP If Statement
 PHP if statement allows conditional execution of code. It is executed
if condition is true.
 If statement is used to executes the block of code exist inside the if
statement only if the specified condition is true.
 Syntax
if(condition){
//code to be executed
}
 Example
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>
 Output:
12 s less than 100

(ii)
PHP If-else Statement
 PHP if-else statement is executed whether condition is true or false.
 If-else statement is slightly different from if statement. It executes
one block of code if the specified condition is true and another block
of code if the condition is false.
 Syntax
if(condition){

Unit I
Expressions and Control Statements in PHP Page 17
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

//code to be executed if true


}else
{
//code to be executed if false
}
 Example
<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>
 Output:
12 is even number

(iii) PHP If-else-if Statement(else-if ladder)


 The PHP if-else-if is a special statement used to combine multiple
if.else statements. So, we can check multiple conditions using this
statement.
 Syntax
if (condition1){
//code to be executed if condition1 is true
} elseif (condition2){
//code to be executed if condition2 is true
} elseif (condition3){
//code to be executed if condition3 is true
...
} else{
//code to be executed if all given conditions are false
}
 Example
<?php
$marks=69;
if ($marks<33){
echo "fail";
}
else if ($marks>=34 && $marks<50) {
echo "D grade";
}
Unit I
Expressions and Control Statements in PHP Page 18
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

else if ($marks>=50 && $marks<65) {


echo "C grade";
}
else if ($marks>=65 && $marks<80) {
echo "B grade";
}
else if ($marks>=80 && $marks<90) {
echo "A grade";
}
else if ($marks>=90 && $marks<100) {
echo "A+ grade";
}
else {
echo "Invalid input";
}
?>
 Output:
B Grade

(iv)
PHP nested if Statement
 The nested if statement contains the if block inside another if block.
The inner if statement executes only when specified condition in
outer if statement is true.
 Syntax
if (condition) {
//code to be executed if condition is true
if (condition) {
//code to be executed if condition is true
}
}
 Example
<?php
$age = 23;
$nationality = "Indian";
//applying conditions on nationality and age
if ($nationality == "Indian")
{
if ($age >= 18) {
echo "Eligible to give vote";
}
Unit I
Expressions and Control Statements in PHP Page 19
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

else {
echo "Not eligible to give vote";
}
}
?>
 Output:
Eligible to give vote

(v) PHP Switch


 PHP switch statement is used to execute one statement from multiple
conditions. It works like PHP if-else-if statement.
 Syntax:
switch(expression){
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}
 Example
<?php
$num=20;
switch($num){
case 10:
echo("number is equals to 10");
break;
case 20:
echo("number is equal to 20");
break;
case 30:
echo("number is equal to 30");
break;
default:
echo("number is not equal to 10, 20 or 30");
}
?>
Unit I
Expressions and Control Statements in PHP Page 20
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 Output:
number is equal to 20

(vi) PHP Break Statement


 PHP break statement breaks the execution of the current for, while,
dowhile, switch, and for-each loop. If you use break inside inner
loop, it breaks the execution of inner loop only.
 The break keyword immediately ends the execution of the loop or
switch structure.
 It breaks the current flow of the program at the specified condition
and program control resumes at the next statements outside the loop.
 The break statement can be used in all types of loops such as while,
dowhile, for, foreach loop, and also with switch case .
 Syntax

statements;
break;

 Example
Let's see a simple example to break the execution of for loop if value
of i is equal to 5.
<?php
for($i=1;$i<=10;$i++){
echo "$i <br/>";
if($i==5){
break;
}
}
?>

Output:
1
2
3
4
5

Unit I
Expressions and Control Statements in PHP Page 21
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

(vii) PHP continue statement

 The PHP continue statement is used to continue the loop. It continues


the current flow of the program and skips the remaining code at the
specified condition.
 The continue statement is used within looping and switch control
structure when you immediately jump to the next iteration.
 The continue statement can be used with all types of loops such as -
for, while, do-while, and foreach loop. The continue statement allows
the user to skip the execution of the code for the specified condition.

 Syntax
The syntax for the continue statement is given below:
Statements;
Continue;

 Example
In the following example, we will print only those values of i and j
that are same and skip others.

<?php
//outer loop
for ($i =1; $i<=3; $i++) {
//inner loop
for ($j=1; $j<=3; $j++) {
if (!($i == $j) ) {
continue; //skip when i and j does not have same values
}
echo $i.$j;
echo "</br>";
}
}
?>

Output:
11
22
33

Unit I
Expressions and Control Statements in PHP Page 22
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

1.4 Loop Control Structure


(i) PHP While Loop

 PHP while loop can be used to traverse set of code like for loop. The
while loop executes a block of code repeatedly until the condition is
FALSE. Once the condition gets FALSE, it exits from the body of
loop.It should be used if the number of iterations is not known.
 The while loop is also called an Entry control loop because the
condition is checked before entering the loop body. This means that
first the condition is checked. If the condition is true, the block of
code will be executed.
 Syntax
while(condition){
//code to be executed
}
 Alternative Syntax
while(condition):
//code to be executed
endwhile;
PHP While Loop Flowchart
PHP While Loop Example
<?php
$n=1;
while($n<=10){
echo "$n<br/>";
$n++;
}
?>
 Output:
1
2
3
4
5
6
7
8
9
10

Unit I
Expressions and Control Statements in PHP Page 23
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

(ii) PHP do-while loop

 PHP do-while loop can be used to traverse set of code like php while
loop. The PHP do-while loop is guaranteed to run at least once.
 The PHP do-while loop is used to execute a set of code of the
program several times. If you have to execute the loop at least once
and the number of iterations is not even fixed, it is recommended to
use the do-while loop.
 It executes the code at least one time always because the condition is
checked after executing the code.
 The do-while loop is very much similar to the while loop except the
condition check.
 The main difference between both loops is that while loop checks the
condition at the beginning, whereas do-while loop checks the
condition at the end of the loop.
 Syntax
do{
//code to be executed
}while(condition);
Flowchart
Example
<?php
$n=1;
do{
echo "$n<br/>";
$n++;
}while($n<=10);
?>
 Output:
1
2
3
4
5
6
7
8
9
10

Unit I
Expressions and Control Statements in PHP Page 24
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

(iii) PHP For Loop


 PHP for loop can be used to traverse set of code for the specified
number of times.
 It should be used if the number of iterations is known otherwise use
while loop. This means for loop is used when you already know how
many times you want to execute a block of code.
 It allows users to put all the loop related statements in one place. See
in the syntax given below:
 Syntax
for(initialization; condition; increment/decrement){
/code to be executed
}
 Parameters
The php for loop is similar to the java/C/C++ for loop. The
parameters of for loop have the following meanings:
 initialization - Initialize the loop counter value. The initial value
of the for loop is done only once. This parameter is optional.
 condition - Evaluate each iteration value. The loop continuously
executes until the condition is false. If TRUE, the loop execution
continues, otherwise the execution of the loop ends.
 Increment/decrement - It increments or decrements the value of
the variable.

 Example
<?php
for($n=1;$n<=10;$n++)
{
echo "$n<br/>";
}
?>

 Output:
1
2
3
4
5
6
7
8
9
10
Unit I
Expressions and Control Statements in PHP Page 25
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

(iv) PHP foreach Loop


 The foreach loop works only on arrays, and is used to loop through
each key/value pair in an array.

 Syntax
foreach ($array as $value)
{
code to be executed;
}
 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.

 Example
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>

 Output
red
green
blue
yellow

******END *******

Unit I
Expressions and Control Statements in PHP Page 26
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

Important Questions :
1) Write Any five Advantages of PHP.
2) State the use of “$” sign in PHP.
3) Write the syntax of PHP.
4) Explain the term :
a) Variable
b) Expression
5) Explain any Four data types in PHP.
6) List different types of operators in PHP.
7) Write a program using foreach loop.

Unit I
Expressions and Control Statements in PHP Page 27
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

2.1  Creating and Manipulating Array


 Types of Arrays
 Indexed Array
 Associative Array
 Multidimensional Array
2.2  Extracting Data from Arrays
 Implode
 Explode
 Array flip
2.3 Traversing Arrays
2.4 Functions and its Types :
 User Defined
 Variable Function
 Anonymous Function
2.5 Operations on String and String Functions :
 str_word_count()
 strlen()
 strrev()
 strpos()
 str_replace()
 ucwords()
 strtoupper()
 strtolower()
 strcmp()
2.6  Basic Graphics Concepts
 Creating Images
 Images with text
 Scaling Images
 Creation of PDF document

Unit II
Arrays, Functions and Graphics Page 1
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

2.1 Array
Definition:
An array is an ordered collection of elements. The elements are of same data type or
different data type. Each element has a value, and is identified by a key. Each array
has its own unique keys. The keys can be either integer numbers or strings.

(1) Creating and Manipulating Array:


There are following ways of creating array:
1) Using array() function
2) Using array identifier

1) Using array() function:


 In PHP, the array() function is used to create an array:
array( );
 Syntax:
$ArrayName = array(value1,value2….valueN);

 In Numeric array each elements are assigned a numeric key value starting
from 0 for first elements and so on.

 Example:
<?php
$name=array(“Archana”, “Sanket”, “Helisha”);
print_r($name);
?>
 Output:
Array([0] => Archana [1] => Sanket [2]=>Helisha)

2) Using array identifier


 In PHP, we can also create an array using array identifier.

 Syntax:
$ArrayName [ ] = “value”;

 Example:
<?php
$name[ ] = “Mohan”;
$name[ ] = “Helisha”;

Unit II
Arrays, Functions and Graphics Page 2
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

print_r($name);
?>

 Output:
Array([0] =>Arpan [1] =>Mohan [2]=>Helisha)

Defining Starting index:


 By default starting index of an array is 0. It is incremented by 1 for each
successive elements of an array. But it is also possible to define start index of
an array.

 Example:
<?php
$name = array(19=> “Arpan”, “Charmi”, “Reshma”);
print_r($name);
?>

 Output:
Array ([19]=> Arpan [20]=>Charmi [21]=>Reshma)

Adding More Elements To Array:


 Once an array id created we can add more elements to an array using array
identifier.

 Example:
<?php
$name=array(“Arpan”, “Sohan”, “Helisha”);
print_r($name);
echo “<br>”;
$name[ ] = “Sagar”;
print_r($name);
?>

 Output:
Array([0] =>Arpan [1] =>Sohan [2]=>Helisha)
Array([0] =>Arpan [1] =>Sohan [2]=>Helisha [3]=>Sagar)

Unit II
Arrays, Functions and Graphics Page 3
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

(2) Types of Arrays


There are three different kinds of arrays and each array value is accessed using an
array index.

1. Indexed Array
These arrays can store numbers, strings and any object but their index will be pre
presented by numbers. By default array index starts from zero.

Example
Following is the example showing how to create and access numeric arrays.
Here we have used array()function to create array. This function is explained in
function reference.

<html>
<body>
<?php
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
echo"<pre>";
Print_r($numbers);
echo"</pre>";?>
</body>
</html>

Output:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5

Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)

Unit II
Arrays, Functions and Graphics Page 4
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

2. Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality
but they are different in terms of their index. Associative array will have their
index as string so that you can establish a strong association between key and
values.

Example

<html>
<body>
<?php
$salaries = array(
"mohammad" => 2000, "Dinesh" => 1000, "Surabhi" => 500
);
echo "Salary of Arjun is ". $salaries['Arjun'] . "<br />";
echo "Salary of Dinesh is ". $salaries['Dinesh']. "<br />";
echo "Salary of Surabhi is ". $salaries['Surabhi']. "<br />";
echo "<pre>";
print_r($salaries);
echo "</pre>";
?>
</body>
</html>

Output
Salary of Arjun is 2000
Salary of Dinesh is 1000
Salary of Surabhi is 500
Array
(
[Arjun] => 2000
[Dinesh] => 1000
[Surabhi] => 500
)

Unit II
Arrays, Functions and Graphics Page 5
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

3. Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array.
And each element in the sub-array can be an array, and soon. Values in the multi-
dimensional array are accessed using multiple indexes.

Example
In this example we create a two dimensional array to store marks of three students
in three subjects:
<html>
<body>
<?php
$marks = array(
"Arjun" => array
(
"physics" => 35, "maths" => 30, "chemistry" => 39
),
"Dinesh" => array
(
"physics" => 30, "maths" => 32, "chemistry" => 29
),
"Surabhi" => array
(
"physics" => 31, "maths" => 22, "chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for Arjun in physics : " ;
echo $marks['Arjun']['physics'] . "<br />";
echo "Marks for Dinesh in maths : ";
echo $marks['Dinesh']['maths'] . "<br />";
echo "Marks for Surabhi in chemistry : " ;
echo $marks['Surabhi']['chemistry'] . "<br />";
echo "<pre>";
print_r($marks);
echo "</pre>";
?>
</body>
</html>

Output:
Marks for Arjun in physics : 35
Marks for Dinesh in maths : 32
Marks for Surabhi in chemistry : 39

Unit II
Arrays, Functions and Graphics Page 6
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

Array
(
[Arjun] => Array
(
[physics] => 35
[maths] => 30
[chemistry] => 39
)

[Dinesh] => Array


(
[physics] => 30
[maths] => 32
[chemistry] => 29
)

[Surabhi] => Array


(
[physics] => 31
[maths] => 22
[chemistry] => 39
)

)
2.2 In-Built Functions of Array
1) sizeof($arr)
 This function returns the number of elements in an array. Use this function to
find out how many elements an array contains; this information is most
commonly used to initialize a loop counter when processing the array.
 Example:
<?php
$data = array("red", "green", "blue");
echo "Array has " . sizeof($data) . " elements";
?>
 Output
Array has 3 elements

2) array_values($arr)
 This function accepts a PHP array and returns a new array containing only its
values (not its keys). Its counterpart is the array_keys() function. Use this
function to retrieve all the values from an associative array.
 Example
<?php
Unit II
Arrays, Functions and Graphics Page 7
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

$data = array("hero" => "Holmes", "villain" => "Moriarty");


print_r(array_values($data));
?>
 Output
Array
(
[0] => Holmes
[1] => Moriarty
)

3) array_keys($arr)
 This function accepts a PHP array and returns a new array containing only its
keys (not its values). Its counterpart is the array_values() function. Use this
function to retrieve all the keys from an associative array.
 Example
<?php
$data = array("hero" => "Holmes", "villain" => "Moriarty");
print_r(array_keys($data));
?>
 Output:
Array
(
[0] => hero
[1] => villain
)

4) array_pop($arr)
 This function removes an element from the end of an array.
 Example
<?php
$data = array("Donald", "Jim", "Tom");
array_pop($data);
print_r($data);
?>
 Output
Array
(
[0] => Donald
[1] => Jim
)
5)
array_push($arr, $val)
 This function adds an element to the end of an array.
 Example
Unit II
Arrays, Functions and Graphics Page 8
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

<?php
$data = array("Donald", "Jim", "Tom");
array_push($data, "Harry");
print_r($data);
?>
 Output
Array
(
[0] => Donald
[1] => Jim
[2] => Tom
[3] => Harry
)

6)
array_shift($arr)
 This function removes an element from the beginning of an array.
 Example
<?php
$data = array("Donald", "Jim", "Tom");
array_shift($data);
print_r($data);
?>
 Output
Array
(
[0] => Jim
[1] => Tom
)

7) array_unshift($arr, $val)
 This function adds an element to the beginning of an array.
 Example
<?php
$data = array("Donald", "Jim", "Tom");
array_unshift($data, "Sarah");
print_r($data);
?>
 Output:
Array(
[0] => Sarah
[1] => Donald
[2] => Jim
[3] => Tom
)
Unit II
Arrays, Functions and Graphics Page 9
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

8) array_flip($arr)
 The function exchanges the keys and values of a PHP associative array. Use this
function if you have a tabular (rows and columns) structure in an array, and you
want to interchange the rows and columns.
 Example
<?php
$data = array("a" => "apple", "b" => "ball");
print_r(array_flip($data));
?>
 Output
Array
(
[apple] => a
[ball] => b )

9) array_reverse($arr)
 The function reverses the order of elements in an array. Use this function to re-
order a sorted list of values in reverse for easier processing—for example, when
you’re trying to begin with the minimum or maximum of a set of ordered values.
 Example
<?php
$data = array(10, 20, 25, 60);
print_r(array_reverse($data));
?>
 Output
Array
(
[0] => 60
[1] => 25
[2] => 20
[3] => 10
)

10) array_merge($arr)
 This function merges two or more arrays to create a single composite array. Key
collisions are resolved in favor of the latest entry. Use this function when you
need to combine data from two or more arrays into a single structure. For
example, records from two different SQL queries.
 Example
<?php
$data1 = array("cat", "goat");
$data2 = array("dog", "cow");
Unit II
Arrays, Functions and Graphics Page 10
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

print_r(array_merge($data1, $data2));
?>
 Output
Array
(
[0] => cat
[1] => goat
[2] => dog
[3] => cow )

11) array_rand($arr)
 This function selects one or more random elements from an array. Use this
function when you need to randomly select from a collection of discrete values.
For example, picking a random color from a list.
 Example
<?php
$data = array("white", "black", "red");
echo "Today's color is " . $data[array_rand($data)];
?>
 Output
Today’s color is red

12)
array_search($search, $arr)
 This function searches the values in an array for a match to the search term, and
returns the corresponding key if found. If more than one match exists, the key of
the first matching value is returned. Use this function to scan a set of index-value
pairs for matches, and return the matching index.
 Ex-
<?php
$data = array("blue" => "#0000cc", "black" => "#000000", "green" =>
"#00ff00");
echo "Found " . array_search("#0000cc", $data);
?>
 Output
Found blue

13) array_slice($arr, $offset, $length)

 This function is useful to extract a subset of the elements of an array, as another


array. Extracting begins from array offset $offset and continues until the array
slice is $length elements long. Use this function to break a larger array into
smaller ones—for example, when segmenting an array by size (“chunking”) or
type of data.

Unit II
Arrays, Functions and Graphics Page 11
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 Example
<?php
$data = array("vanilla", "strawberry", "mango", "peaches");
print_r(array_slice($data, 1, 2));
?>
 Output
Array
(
[0] => strawberry
[1] => mango
)

14) array_unique($data)
 This function strips an array of duplicate values. Use this function when you
need to remove non-unique elements from an array. For example, when creating
an array to hold values for a table’s primary key.
 Example
<?php
$data = array(1,1,4,6,7,4);
print_r(array_unique($data));
?>
 Output
Array
(
[0] => 1
[3] => 6
[4] => 7
[5] => 4
)

15) array_change_key_case()
 PHP array_change_key_case() function changes the case of all key of an array. It
changes case of key only.
 Example
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
print_r(array_change_key_case($salary,CASE_UPPER));
?>
 Output:
Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )
 Example
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
print_r(array_change_key_case($salary,CASE_LOWER));
?>
Unit II
Arrays, Functions and Graphics Page 12
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 Output:
Array ( [sonoo] => 550000 [vimal] => 250000 [ratan] => 200000 )

16) array_chunk()
 PHP array_chunk() function splits array into chunks. By using array_chunk()
method, you can divide array into many parts.
 Example
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
print_r(array_chunk($salary,2));
?>
 Output:
Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
[1] => Array ( [0] => 200000 )
)

17) array_intersect()
 PHP array_intersect() function returns the intersection of two array. In other
words, it returns the matching elements of two array.
 Example
<?php
$name1=array("sonoo","john","vivek","smith");
$name2=array("umesh","sonoo","kartik","smith");
$name3=array_intersect($name1,$name2);
foreach( $name3 as $n )
{
echo "$n<br />";
}
?>
 Output:
sonoo
smith

18)
implode()
 The implode() is a built-in function in PHP and is used to join the elements of an
array. It works exactly same as that of join() function.
 If we have an array of elements, we can use the implode() function to join them
all to form one string. We basically join array elements with a string. Just like
join() function , implode() function also returns a string formed from the
elements of an array.

Unit II
Arrays, Functions and Graphics Page 13
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 Syntax :
implode(separator,array)

 Parameters:
The implode() function accepts two parameter out of which one is optional and
one is mandatory.
1) separator: This is an optional parameter and is of string type. The values of
the array will be join to form a string and will be separated by the separator
parameter provided here. This is optional, if not provided the default is “” (i.e.
an empty string).
2) array: The array whose value is to be joined to form a string.

 Return Type:
The return type of implode() function is string. It will return the joined string
formed from the elements of array.

 Example:
<?php
// PHP Code to implement join function

$a= array('I','like','PHP');

// Join without separator


print_r(implode($a));
echo"</br>";

// Join with separator


print_r(implode("-",$a));
echo"</br>";
print_r(implode(" ",$a));
?>

 Output:
IlikePHP
I-like-PHP
I like PHP

19)
explode()
 explode() is a built in function in PHP used to split a string in different strings.
The explode() function splits a string based on a string delimiter, i.e. it splits the
string wherever the delimiter character occurs. This functions returns an array
containing the strings formed by splitting the original string.

Unit II
Arrays, Functions and Graphics Page 14
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 Syntax :
explode(separator, String, limit)
 Parameters:
The explode function accepts three parameters of which two are compulsory and
one is optional.
1) separator : This character specifies the critical points or points at which the
string will split, i.e. whenever this character is found in the string it symbolizes
end of one element of the array and start of another.
2) String : The input string which is to be split in array.
3) limit : This is optional. It is used to specify the number of elements of the
array. This parameter can be any integer ( positive , negative or zero)
 Positive (N): When this parameter is passed with a positive value it means
that the array will contain this number of elements. If the number of
elements after separating with respect to the separator emerges to be greater
than this value the first N-1 elements remain the same and the last element
is the whole remaining string.
 Negative (N):If negative value is passed as parameter then the last N
element of the array will be trimmed out and the remaining part of the array
shall be returned as a single array.
 Zero : If this parameter is Zero then the array returned will have only one
element i.e. the whole string.
 Return Type:
The return type of explode() function is array of strings.
 Example:
<?php
echo"<pre>";
$OriginalString = "Hello, How can we help you?";
echo"Without optional parameter limit";
print_r(explode(" ",$OriginalString));
print_r(explode(",",$OriginalString));
echo"</br>";
echo"with positive limit";
echo"</br>";
print_r(explode(" ",$OriginalString,3));
echo"</br>";
print_r(explode(",",$OriginalString,1));
echo"</br>";
echo"with negative limit";
echo"</br>";
print_r(explode(" ",$OriginalString,-1));
echo"</br>";
print_r(explode(" ",$OriginalString,-3));
echo"</pre>";
?>

Unit II
Arrays, Functions and Graphics Page 15
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 Output:
Without optional parameter limitArray
(
[0] => Hello,
[1] => How
[2] => can
[3] => we
[4] => help
[5] => you?
)
Array
(
[0] => Hello
[1] => How can we help you?
)

with positive limit


Array
(
[0] => Hello,
[1] => How
[2] => can we help you?
)

Array
(
[0] => Hello, How can we help you?
)

with negative limit


Array
(
[0] => Hello,
[1] => How
[2] => can
[3] => we
[4] => help
)

Array
(
[0] => Hello,
[1] => How
[2] => can
)

Unit II
Arrays, Functions and Graphics Page 16
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

20) Extract()
 The extract() Function is an inbuilt function in PHP. The extract() function does
array to variable conversion. That is it converts array keys into variable names
and array values into variable value.

 Syntax :
extract($array, $extract_rule, $prefix)

 Parameters:
The extract() function accepts three parameters, out of which one is compulsory
and other two are optional.
1) $array: This parameter is required. This specifies the array to use.
2) $extract_rule: This parameter is optional. The extract() function checks for
invalid variable names and collisions with existing variable names. This
parameter specifies how invalid and colliding names will be treated. This
parameter can take the following values:
 EXTR_OVERWRITE: This rule tells that if there is a collision, overwrite
the existing variable.
 EXTR_SKIP: This rule tells that if there is a collision, don’t overwrite the
existing variable.
 EXTR_PREFIX_SAME: This rule tells that if there is a collision then
prefix the variable name according to $prefix parameter.
 EXTR_PREFIX_ALL: This rule tells that prefix all variable names
according to $prefix parameter.
 $prefix: This parameter is optional. This parameter specifies the prefix. The
prefix is automatically separated from the array key by an underscore
character. Also this parameter is required only when the parameter
$extract_rule is set to EXTR_PREFIX_SAME, EXTR_PREFIX_ALL.
 Return Type:
The return value of extract() function is an integer and it represents the number of
variables successfully extracted or imported from the array.

 Example:
<?php

$KR="KARNATAKA";
$state = array("AS"=>"ASSAM", "OR"=>"ORISSA", "KR"=>"KERALA");

echo $KR."</br>";
echo"</br>";

extract($state);

echo"after using extract() function without optional parameter</br>";

Unit II
Arrays, Functions and Graphics Page 17
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

echo"$AS</br>$KR</br>$OR";
echo"</br>";
echo"</br>";
echo"With Extract Rules-Prefix same";
echo"</br>";
extract($state,EXTR_PREFIX_SAME,"key");
echo"$AS</br>$KR</br>$key_KR</br>$OR";
echo"</br>";
echo"</br>";
echo"With Extract Rules-Prefix all";
echo"</br>";
extract($state,EXTR_PREFIX_ALL,"key");
echo"$key_AS</br>$key_KR</br>$key_OR</br>$KR";
?>

 Output:
KARNATAKA

after using extract() function without optional parameter


ASSAM
KERALA
ORISSA

With Extract Rules-Prefix same


ASSAM
KARNATAKA
KERALA
ORISSA

With Extract Rules-Prefix all


ASSAM
KERALA
ORISSA
KARNATAKA

21) Compact()
 The compact() function creates an array from variables and their values. Any
strings that does not match variable names will be skipped.

 Syntax :
compact(var1, var2...)

 Parameters: The compact() function accepts any no. of variables. Atleast one
variable is compulsory and others may be optional.
1) var1- Required. Can be a string with the variable name, or an array of

Unit II
Arrays, Functions and Graphics Page 18
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

variables
2) var2,.. - Optional. Can be a string with the variable name, or an array of
variables. Multiple parameters are allowed.

 Return Type: Returns an array with all the variables added to it.

 Example:
<?php
echo"<pre>";
$firstname = "Akshay";
$lastname = "Deshapande";
$age = "41";

$name = array("firstname", "lastname");


$result = compact($name, "location", "age");

print_r($result);
echo"</pre>";
?>

 Output:
Array
(
[firstname] => Akshay
[lastname] => Deshapande
[age] => 41
)

Sorting Arrays in PHP


 Sorting is a process by which we can arrange the elements of a list in a specific
order i.e. ascending or descending order. We can say sorting is the process of
putting a list or a group of items in a specific order. Sorting may be alphabetical
or numerical.
 In PHP, sorting is a process of arranging the elements of an array in a specific
order i.e. ascending or descending order. Using sorting you can analyze a list in a
more effective way. You can sort an array by value, key or randomly. In the most
situations we need to sort an array by value.
 Some sorting functions are as follows:
1) sort()
2) asort()
3) rsort()
4) arsort()

Unit II
Arrays, Functions and Graphics Page 19
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

1) sort()
Using the sort() function you can sort easily and simply. The example of the sort()
function is as follows:

Example:
<?php
$name=array ("Anuj","Sanjeev","Manish","Rahul");
echo "<b>Before sorting the values are:</b>".'<br>';
print_r($name).'<br>'.'<br>';
sort($name);
echo"<br/>";
echo"<br/>";
echo "<b>After sorting values become:</b>".'<br>';
print_r($name).'<br>';
?>

Output:
Before sorting the values are:
Array ( [0] => Anuj [1] => Sanjeev [2] => Manish [3] => Rahul )

After sorting values become:


Array ( [0] => Anuj [1] => Manish [2] => Rahul [3] => Sanjeev )

2) rsort() function
The rsort() function is used to sort an array in descending (alphabetic) order

Example:
<?php
$name=array ("Anuja","Sanjeev","Manisha","Rahul");
echo "<b>Before sorting the values are:</b>".'<br>';
print_r($name).'<br>'.'<br>';
rsort($name);
echo"<br/>";
echo"<br/>";
echo "<b>After sorting values become:</b>".'<br>';
print_r($name).'<br>';
?>

Output:
Before sorting the values are:
Array ( [0] => Anuja [1] => Sanjeev [2] => Manisha [3] => Rahul )

After sorting values become:


Array ( [0] => Sanjeev [1] => Rahul [2] => Manisha [3] => Anuja )

Unit II
Arrays, Functions and Graphics Page 20
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

3) asort() function
In the example above you saw that the elements of the array are arranged in
ascending (alphabetically) order. The asort() function sorts an array and also
maintains the index position.

Example
<?php
$name=array
("DSU"=>22317,"DCC"=>22414,"WBP"=>22619,"CSS"=>22519);
echo "<b>Before sorting the values are:</b>".'<br>';
print_r($name).'<br>'.'<br>';
asort($name);
echo"<br/>";
echo"<br/>";
echo "<b>After sorting values become:</b>".'<br>';
print_r($name).'<br>';
?>
Output
Before sorting the values are:
Array ( [DSU] => 22317 [DCC] => 22414 [WBP] => 22619 [CSS] => 22519 )

After sorting values become:


Array ( [DSU] => 22317 [DCC] => 22414 [CSS] => 22519 [WBP] => 22619 )

4) arsort() function
The arsort() function is a combination of asort() + rsort(). The arsort() function will
sort an array in reverse order and maintain index position.

Example
<?php
$name=array
("DSU"=>22317,"DCC"=>22414,"WBP"=>22619,"CSS"=>22519);
echo "<b>Before sorting the values are:</b>".'<br>';
print_r($name).'<br>'.'<br>';
arsort($name);
echo"<br/>";
echo"<br/>";
echo "<b>After sorting values become:</b>".'<br>';
print_r($name).'<br>';
?>

Unit II
Arrays, Functions and Graphics Page 21
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

Output

Before sorting the values are:


Array ( [DSU] => 22317 [DCC] => 22414 [WBP] => 22619 [CSS] => 22519 )

After sorting values become:


Array ( [WBP] => 22619 [CSS] => 22519 [DCC] => 22414 [DSU] => 22317 )

5) ksort()
The ksort() function sorts an associative array in ascending order, according to
the key.

Example:
<?php
$name=array
("DSU"=>22317,"DCC"=>22414,"WBP"=>22619,"CSS"=>22519);
echo "<b>Before sorting the values are:</b>".'<br>';
print_r($name).'<br>'.'<br>';
ksort($name);
echo"<br/>";
echo"<br/>";
echo "<b>After sorting values become:</b>".'<br>';
print_r($name).'<br>';
?>

Output:
Before sorting the values are:
Array ( [DSU] => 22317 [DCC] => 22414 [WBP] => 22619 [CSS] => 22519
)

After sorting values become:


Array ( [CSS] => 22519 [DCC] => 22414 [DSU] => 22317 [WBP] => 22619
)

Unit II
Arrays, Functions and Graphics Page 22
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

6) krsort()
The krsort() function sorts an associative array in descending order,
according to the key.

Example:
<?php
$name=array
("DSU"=>22317,"DCC"=>22414,"WBP"=>22619,"CSS"=>22519);
echo "<b>Before sorting the values are:</b>".'<br>';
print_r($name).'<br>'.'<br>';
krsort($name);
echo"<br/>";
echo"<br/>";
echo "<b>After sorting values become:</b>".'<br>';
print_r($name).'<br>';
?>

Output:
Before sorting the values are:
Array ( [DSU] => 22317 [DCC] => 22414 [WBP] => 22619 [CSS] => 22519 )

After sorting values become:


Array ( [WBP] => 22619 [DSU] => 22317 [DCC] => 22414 [CSS] => 22519 )

2.3 Traversing Arrays


Array traversing means accessing each element and perform some operations on it.
Array traversing can be done by using simple for and foreach loop. Instead we can
use inbuilt iteration functions

The Iterator Functions


Every PHP array keeps track of the current element you're working with; the pointer
to the current element is known as the iterator. PHP has functions to set, move, and
reset this iterator.

Unit II
Arrays, Functions and Graphics Page 23
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

Example:
<?php
Output :
$colors = array("red", "green", "blue", "yellow"); Array Elements are
echo"Array Elements are<br>"; red
foreach ($colors as $value) { green
blue
echo "$value <br>";
yellow
} -----------------------------------
echo"-----------------------------------<br>"; Using Iterator Function
echo "Using Iterator Function<br>"; -----------------------------------
current=red
echo"-----------------------------------<br>";
-----------------------------------
echo"current=".current($colors)."<br>"; next=green
echo"-----------------------------------<br>"; -----------------------------------
echo"next=".next($colors)."<br>"; next=blue
-----------------------------------
echo"-----------------------------------<br>"; previous=green
echo"next=".next($colors)."<br>"; -----------------------------------
echo"-----------------------------------<br>"; key=1
echo"previous=".prev($colors)."<br>"; -----------------------------------
reset=red
echo"-----------------------------------<br>"; -----------------------------------
echo"key=".key($colors)."<br>"; key=0
echo"-----------------------------------<br>"; -----------------------------------
echo"reset=".reset($colors)."<br>"; current=red
-----------------------------------
echo"-----------------------------------<br>"; end=yellow
echo"key=".key($colors)."<br>"; -----------------------------------
echo"-----------------------------------<br>"; each=
echo"current=".current($colors)."<br>"; Array
(
echo"-----------------------------------<br>"; [1] => yellow
echo"end=".end($colors)."<br>"; [value] =>
yellow
echo"-----------------------------------<br>"; [0] => 3
echo"each=<pre>"; [key] => 3
)
print_r(each($colors));
echo"</pre>";
?>

The iterator functions are:

Sr. Function Description


No.
1) current() Returns the element currently pointed at by the iterator
2) reset() Moves the iterator to the first element in the array and
returns it
3) next() Moves the iterator to the next element in the array and
returns it
4) prev() Moves the iterator to the previous element in the array
and returns it

Unit II
Arrays, Functions and Graphics Page 24
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

5) end() Moves the iterator to the last element in the array and
returns it
6) each() Returns the key and value of the current element as an
array and moves the iterator to the next element in the
array
7) key() Returns the key of the current element

2.4 Functions
A function is a block of statements that can be used repeatedly in a program. A
function will not execute immediately when page loads. A function will be executed
by a call to the function.

1) User Defined Function:


 A user defined function declaration starts with the word "function“.A function
name can start with a letter or underscore (not a number).

 Syntax
function functionName()
{
code to be executed;
}
functionName(); ----------- Function call

 Example
<?php
function writeMsg( )
{
echo "Hello world!";
}
writeMsg(); // call the function
?>

 Output
Hello world!

2) Parameterized Function:
 PHP gives you option to pass your parameters inside a function. You can pass as
many as parameters your like. These parameters work like variables inside your
function. Following example takes two integer parameters and add them together
and then print them.

Unit II
Arrays, Functions and Graphics Page 25
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 Syntax
function functionName(variable1,variable2…)
{
code to be executed;
}
functionName(variable1,variable2…); -----------  Function call

 Example
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}

addFunction(10, 20);
?>

 Output
Sum of the two numbers is : 30

3)
Return Type Function:
 A function can return a value using the return statement. return stops the
execution of the function and sends the value back to the calling code.

 Syntax
function functionName()
{
code to be executed;
return value;
}
Value=functionName(); ----------- Function call

 Example
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value";
?>
 Output
Returned value from the function : 30

Unit II
Arrays, Functions and Graphics Page 26
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

4) Variable Function:
 PHP supports the concept of variable functions. This means that if a variable
name has parentheses appended to it, PHP will look for a function with the same
name as whatever the variable evaluates to, and will attempt to execute it.
 Syntax
function functionName()
{
code to be executed;
}
$variableName=”functionName”;
$variableName(); ----------- Function call

 Example
<?php
function add($x, $y){
echo $x+$y;
}
$var="add";
$var(10,20);
?>

 Output
30

5)
Anonymous Function:
 Anonymous function is a function without any user defined name. Such a
function is also called closure or lambda function. Sometimes, you may want a
function for one time use. Closure is an anonymous function which closes over
the environment in which it is defined. You need to specify use keyword in
it.Most common use of anonymous function to create an inline callback function.
 There is no function name between the function keyword and the opening
parenthesis.
 There is a semicolon after the function definition because anonymous function
definitions are expressions
 Function is assigned to a variable, and called later using the variable’s name.
 When passed to another function that can then call it later, it is known as a
callback.
 Return it from within an outer function so that it can access the outer function’s
variables. This is known as a closure.

Unit II
Arrays, Functions and Graphics Page 27
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 Syntax
$variableName=function ($arg1, $arg2)
{
return $val;
};
$variableName(); ----------- Function call

 Example
<?php
$var = function ($x)
{
return pow($x,3);
};
echo "cube of 3 = " . $var(3);
?>

 Output
cube of 3 = 27

6)
Function with default Arguments:
 If we call a PHP function without arguments, PHP functions takes the default
value as an argument

 Syntax
function functionName(variable1, variable2)
{
code to be executed;
}
$variableName=”functionName”;
$variableName(); ------Both arguments default
$variableName(variable1); ------variable2 is default
$variableName( ,variable2); ------variable1 is default

 Example
<?php
function weightHeight($defaultweight = 60,$defaultheight = 170) {
echo "The Weight is : $defaultweight <br>";
echo "The Height is : $defaultheight <br><br>";
}
weightHeight(45);
weightHeight();
weightHeight(70,160);
?>
Unit II
Arrays, Functions and Graphics Page 28
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 Output
The Weight is : 45
The Height is : 170

The Weight is : 60
The Height is : 170

The Weight is : 70
The Height is : 160

2.5 String
 A string is a series of characters. There are exactly 256 different characters
possible.
 The string, like a variable, will have to be created first. There are two ways to use
a string in PHP – you can store it in a function or in a variable. In the example
below, we will create a string twice – the first time storing it in a variable, and the
second time – in a function, in our case – an echo
 Basic Example
<?php
$myString = "This is a string!";
echo "This is a string!</br>";
echo $myString;
?>
 The output of this PHP file will be:
This is a string!
This is a string!

String Functions:
1)
Str_word_count():
 The str_word_count() function counts the number of words in a string.

 Syntax
str_word_count(string,return,char)

 Parameters
1) string - Required. Specifies the string to check
2) return Optional. Specifies the return value of the str_word_count() function.
Possible values:
 0 - Default. Returns the number of words found
 1 - Returns an array with the words from the string
 2 - Returns an array where the key is the position of the word in the
string, and value is the actual word
3) char Optional. Specifies special characters to be considered as words.
Unit II
Arrays, Functions and Graphics Page 29
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 Example
<?php
echo"<pre>";
print_r(str_word_count("Hello world!"));
echo"</br>";
print_r(str_word_count("Hello world!",1));
echo"</br>";
print_r(str_word_count("Hello world !",2,"!"));
echo"</br>";
print_r(str_word_count("Hello world !",0,"!"));
echo"</br>";
echo"</pre>";
?>
 Output
2
Array
(
[0] => Hello
[1] => world
)

Array
(
[0] => Hello
[6] => world
[12] => !
)

Strlen():
 The strlen() function returns the length of a string.

 Syntax
strlen(string)

 Parameters
string - Required. Specifies the string to check

 Example
<?php
echo strlen("Hello world!");
?>
 Output

Unit II
Arrays, Functions and Graphics Page 30
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

12

Strrev():
 The strrev() function reverses a string.

 Syntax
strrev(string)

 Parameters
string - Required. Specifies the string to check

 Example
<?php
echo strrev("Hello world!");
?>

 Output
!dlrow olleH

Strpos():
 The strpos() function finds the position of the first occurrence of a string inside
another string. The strpos() function is case-sensitive.
 strrpos() - Finds the position of the last occurrence of a string inside another
string (case-sensitive)
 stripos() - Finds the position of the first occurrence of a string inside another
string (case-insensitive)
 strripos() - Finds the position of the last occurrence of a string inside another
string (case-insensitive)

 Syntax
strpos(string,find,start)
strrpos(string,find,start)
stripos(string,find,start)
strripos(string,find,start)

 Parameters
1) string - Required. Specifies the string to check
2) find Required. Specifies the string to find
3) start Optional. Specifies where to begin the search. If start is a negative
number, it counts from the end of the string.

 Example

Unit II
Arrays, Functions and Graphics Page 31
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

<?php
$str="Hello world!!! Good morning World. world is beautiful";
echo strpos($str,Hello)."</br>";
echo strrpos($str,world)."</br>";
echo stripos($str,Is)."</br>";
echo strripos($str,world,3)."</br>";
?>

 Output
0
35
41
35

Strstr_replace():
 The str_replace() function replaces some characters with some other
characters in a string.
 This function works by the following rules:
1) If the string to be searched is an array, it returns an array
2) If the string to be searched is an array, find and replace is performed with
every array element
3) If both find and replace are arrays, and replace has fewer elements than
find, an empty string will be used as replace
4) If find is an array and replace is a string, the replace string will be used
for every find value
 Syntax
str_replace(find,replace,string,count)

 Parameters
find- Required. Specifies the value to find
replace- Required. Specifies the value to replace the value in find
string- Required. Specifies the string to be searched
count- Optional. A variable that counts the number of replacements

 Example
<?php
echo “Search an array for the value RED, and then replace it with pink”;
$arr = array("blue","red","green","yellow");
$arr2=array("RGB");
$arr3=array("blue","red","green");
print_r(str_replace("red","pink",$arr,$i));
echo "<br>" . "Replacements: $i</br>";
print_r(str_replace($arr3,$arr2,$arr));
?>

Unit II
Arrays, Functions and Graphics Page 32
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 Output
Search an array for the value RED, and then replace it with pink.
Array ( [0] => blue [1] => pink [2] => green [3] => yellow )
Replacements: 1
Array ( [0] => RGB [1] => [2] => [3] => yellow )

ucwords():
 The ucwords() function converts the first character of each word in a string to
uppercase..

 Syntax
ucwords(string, delimiters)

 Parameters
string -Required. Specifies the string to convert
delimiters-Optional. Specifies the word separator character

 Example
<?php
echo ucwords("hello|world", "|")."</br>";
echo ucwords("hello world");
 ?>

 Output
Hello|World
Hello World

Strtoupper():
 The strtoupper() function converts a string to uppercase.

 Syntax
strtoupper(string)

 Parameters
string - Required. Specifies the string to convert.

 Example
<?php
echo strtoupper("hello world");
?>

 Output
HELLO WORLD

Unit II
Arrays, Functions and Graphics Page 33
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

Strtolower():
 The strtolower() function converts a string to lowercase.

 Syntax
strtolower(string)

 Parameters
string - Required. Specifies the string to convert.

 Example
<?php
echo strtolower("HELLO WORLD");
?>

 Output
hello world

Strcmp():
 The strcmp() function compares two strings.
 The strcmp() function is binary-safe and case-sensitive.
 This function is similar to the strncmp() function, with the difference that you can
specify the number of characters from each string to be used in the comparison
with strncmp().
 The strcasecmp() function compares two strings and it is case-insensitive.
 This function is similar to the strncasecmp() function, with the difference that you
can specify the number of characters from each string to be used in the
comparison with strncasecmp().

 Syntax
strcmp(string1,string2)
strcasecmp(string1,string2)
strncasecmp(string1,string2,length)

 Parameters
strcmp:
string1 Required. Specifies the first string to compare
string2 Required. Specifies the second string to compare

strncmp:
string1 Required. Specifies the first string to compare
string2 Required. Specifies the second string to compare
length Required. Specify the number of characters from each string to be
used in the comparison
Unit II
Arrays, Functions and Graphics Page 34
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 Return Value:
This function returns:
1) 0 - if the two strings are equal
2) <0 - if string1 is less than string2
3) >0 - if string1 is greater than string2

 Example
<?php
echo strcmp("Hello","Hello");
echo "<br>";
echo strcmp("Hello","hELLo");
?>

<?php
echo strncmp("Hello","Hello",6);
echo "<br>";
echo strncmp("Hello","hELLo",6);
?>

 Output
0
-32

0
-32

lcfirst():
 The lcfirst() function converts the first character of a string to lowercase.

 Syntax
lcfirst(string)

 Parameters
string -Required. Specifies the string to convert

 Example
<?php
echo lcfirst("Good Morning");
echo "<br>";
echo lcfirst("good Morning");
?>

 Output
good Morning
good Morning
Unit II
Arrays, Functions and Graphics Page 35
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

2.6 Basic Graphics Function.


PHP can be used to create and manipulate graphical elements independently.
Therefore, the scope and capabilities of PHP graphic handling are very powerful.
It does this with the aid of the GD library, which currently supports image formats in
jpeg, png, gif, and wbmp.

1. Creating Image
We can create an image in PHP using imagecreate() function.
Syntax
$image=imagecreate(width,height)
2.
imagecolorallocate() function:-
The imagecolorallocate() function is an inbuilt function in PHP
which is used to set the color in an image. This function returns a color which is
given in RGB format.
Syntax:
imagecolorallocate ( $image, $red, $green, $blue )
Example
<?php
header ("Content-type: image/png");
$a = ImageCreate (200, 200);//imagecreate(x_size, y_size);
$bg = ImageColorAllocate ($a, 240, 0,0);
//imagecolorallocate(image, red, green, blue)
$txt_color = ImageColorAllocate ($a, 0, 23, 0);
ImageString ($a, 10, 10, 18, "Vesp Chembur Mumbai", $txt_color);//bool
imagestring( $image,
$font, $x, $y, $string, $color )
imagepng($a);s
?>

3. Scaling Images:-
 Scaling an image means making the image either smaller in size or larger in size
than original.
 Using PHP we can resize or rescale the image using the function Imagescale()
 Syntax:
imagescale($image,$new_width,$new_height=1,$mode=IMG_BILINERA_FIX
ED)
 Parameters:
 $image is returned by one of the image creation function.
 $new_width holds the width to scale the image.
 $new_height holds the height to scale the image.
 If the value of this parameter is negative or ommitted then aspect ration of
image will preserve.$mode holds the mode. The value of this parameter is
one of IMG_NEAREST_NEIGHBOUR, IMG_BILINEAR_FIXED,
IMG_BICUBIC, IMG_BICUBIC_FIXED ...
Unit II
Arrays, Functions and Graphics Page 36
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

Creation of PDF document


FPDF is an open source library which is used for creating a PDF document.it is open
source.Link to Download latest version of FPDF class:
http://www.fpdf.org/en/download.php

Features of fpdf
1)It is an open source package,hence freely available on internet
2)It provides the choice of measure unit,page format and margins for pdf page
3)It provides page header and footer management.
4)It provides automatic page breaks to the pdf document
5)It provides the support for various fonts,colors,encoding and image formate.
Example
<?php
require('fpdf183/fpdf.php');
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(60,10,'Hello PHP World!',1,1,'C');
$pdf->Output();
?>

Function use

1. $pdf=new FPDF("L", "mm", "A4");


 L(landscape default), P can be used instead to default to portrait pages.
 mm:-default measurement unit, a choice of point (pt), millimeter (mm),
centimeter (cm) and inch (in)
 size of the page, the choice of A3, A4, A5, Letter & Legal is given.

2. $pdf->AddPage();
Simple function, just add the page, you can tell the function to create either a
portrait (P) or landscape (L) by giving it as a first value (ex: $pdf-
>AddPage("L"), $pdf->AddPage("P")).

3. $pdf->SetFont('Arial','BIU',38);
 font:- Arial,
 BIU' simply tells that we want it to be Bold, Italic & Underlined.
 38 mm in size (because of the default size unit).

4. $pdf->SetTextColor(0,0,255);
color :- red (r), the second is green (g) & blue (b).

5. $pdf->Cell(60,20,'PDF+PHP Test',0,1,C,0);
 mm of width & 20 mm of height,
Unit II
Arrays, Functions and Graphics Page 37
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 String:- ‘PDF+PHP Test’


 Border: 0 means we do not want a border.
 Line position:The 1 next to it means it will go to the beginning of the
next line, if 0 is provided, then it will be to the right of it, if 2 is
provided then it will go below.
 Alignment:The C is just the alignment which is the center of the text
inside the box, possible values are left (L), center (C), right (R).

6. $pdf->Output();
Output a new colorful PDF file!

Unit II
Arrays, Functions and Graphics Page 38
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

3.1 Creating classes and objects


3.2 Constructor and Destructor
3.3 Inheritance
Overloading
Overriding
Cloning object
3.4 Introspection
Serializtion

Unit III
Apply Object Oriented Concepts in PHP Page 1
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

3.1 Classes and Objects

1. What is Object Oriented Programming

 Object-Oriented Programming (OOP) is a programming model that is based


on the concept of classes and objects. As opposed to procedural programming
where the focus is on writing procedures or functions that perform operations
on the data, in object-oriented programming the focus is on the creations of
objects which contain both data and functions together. Object-oriented
programming has several advantages over conventional or procedural style of
programming.

 The most important ones are listed below:


 It provides a clear modular structure for the programs.
 It helps you adhere to the "don't repeat yourself" (DRY) principle, and thus
make your code much easier to maintain, modify and debug. It makes it
possible to create more complicated behavior with less code and shorter
development time and high degree of reusability.
 Let's assume we have a class named Fruit. A Fruit can have properties like
name, color, weight, etc. We can define variables like $name, $color, and
$weight to hold the values of these properties. When the individual objects
(apple, banana, etc.) are created, they inherit all the properties and
behaviors from the class, but each object will have different values for the
properties.
2.
Define a Class
 A class is defined by using the class keyword, followed by the name of the
class and a pair of curly braces ({}).
 All its properties and methods go inside the braces:

 Syntax
<?php
class Fruit {
// code goes here...
}
?>

Unit III
Apply Object Oriented Concepts in PHP Page 2
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 Below we declare a class named Fruit consisting of two properties ($name


and $color) and two methods set_name() and get_name() for setting and
getting the $name property:

 Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>

 In a class, variables are called properties and functions are called methods!
3.
Define Objects
 Classes are nothing without objects! We can create multiple objects from a
class.
 Each object has all the properties and methods defined in the class, but they
will have different property values.
 Objects of a class are created using the new keyword.
 In the example below, $apple and $banana are instances of the class Fruit:
 Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit();

Unit III
Apply Object Oriented Concepts in PHP Page 3
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

$banana = new Fruit();


$apple->set_name('Apple');
$banana->set_name('Banana');
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>

In the example below, we add two more methods to class Fruit, for setting and
getting the $color property:
Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods we use -> to access
function set_name($name) { properties and methods of
$this->name = $name; class , object and -> is
} used to access properties
and methods of his own
function get_name() {
class
return $this->name;
}
function set_color($color) {
$this->color = $color;
}
function get_color() {
return $this->color;
}
}
$apple = new Fruit();
$apple->set_name('Apple');
$apple->set_color('Red');
echo "Name: " . $apple->get_name();
echo "<br>";
echo "Color: " . $apple->get_color();
?>

4. PHP - The $this Keyword


The $this keyword refers to the current object, and is only available inside
methods. Look at the following example:
Example
<?php
class Fruit {
public $name;
}
Unit III
Apply Object Oriented Concepts in PHP Page 4
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

$apple = new Fruit();


?>
So, where can we change the value of the $name property?
There are two ways:

1. Inside the class (by adding a set_name() method and use $this):

Example
<?php
class Fruit {
public $name;
function set_name($name) {
$this->name = $name;
}
}
$apple = new Fruit();
$apple->set_name("Apple");
?>

2. Outside the class (by directly changing the property value):

Example
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
$apple->name = "Apple";
?>

5. PHP - instanceof
You can use the instanceof keyword to check if an object belongs to a specific
class:
Example
<?php
$apple = new Fruit();
var_dump($apple instanceof Fruit); ?>
this keyword is used inside a class, generally within the member functions to
access non-static members of a class(variables or functions) for the current object.

Let's take an example to understand the usage of $this.


<?php
class Person {
// first name of person
private $name;

Unit III
Apply Object Oriented Concepts in PHP Page 5
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

// public function to set value for name (setter method)


public function setName($name) {
$this->name = $name;
}
// public function to get value of name (getter method)
public function getName() {
return $this->name;
}
}
// creating class object
$john = new Person();
// calling the public function to set fname
$john->setName("John Wick");
// getting the value of the name variable
echo "My name is " . $john->getName();
?>
Output
My name is John Wick

 In the program above, we have created a private variable in the class with
name $name and we have two public methods setName() and getName() to
assign a new value to $name variable and to get its value respectively.
 Whenever we want to call any variable of class from inside a member
function, we use $this to point to the current object which holds the variable.
 We can also use $this to call one member function of a class inside another
member function.
 If there is any static member function or variable in the class, we cannot refer
it using the $this.

6 Accessing Properties and Methods


Once you have an object, you can use the -> notation to access methods and
properties of the object:
$object->propertyname
$object->methodname([arg, ... ])

For example:
printf("Ram is %d years old.\n", $ram->age); // property access
$ram->birthday(); // method call
$ram->set_age(21); // method call with arguments

don't use $ when accessing the


object properties or method
* if we are accessing class property or
methods then no need to use $ as they
are properties and not normal variable
Unit III
Apply Object Oriented Concepts in PHP * if there is variable normally declared Page 6
outside the class then we have to use $
sign while accessing it
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

3.2 Constructor and Desctructor


 To create and initialize a class object in a single step, PHP provides a special
method called as Constructor, which is used to construct the object by
assigning the required property values while creating the object.
 Destructor method is used for destroying the object.

Syntax for defining Constructor and Destructor


__construct() and __destruct().

Example:
<?php
class <CLASS_NAME> {
// constructor
function __construct() {
// initialize the object properties
}
// destructor
function __destruct() {
// clearing the object reference
}
}
?>
 Constructor can accept arguments, whereas destructors won't have any
argument because a destructor's job is to destroy the current object reference.
1.
PHP Constructor:-
Let's take the example of a class Person which has two properties, fname and
lname, for this class we will define a constructor for initialising the class
properties(variables) at the time of object creation.
<?php
class Person {
// first name of person
private $fname;
// last name of person
private $lname;
// Constructor
public function __construct($fname, $lname) {
echo "Initialising the object...<br/>";
$this->fname = $fname;
$this->lname = $lname;
}
// public method to show name
public function showName() {
echo "The Legend of India: " . $this->fname . " " . $this->lname;
}
Unit III
Apply Object Oriented Concepts in PHP Page 7
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

}
// creating class object
$j = new Person("Bhagat", "Singh");
$j->showName();
?>

Output:
Initialising the object...
The Legend of India: Bhagat Singh

 While earlier, we were using the -> operator to set values for the variables or
used the setter methods, in case of a constructor method, we can assign
values to the variables at the time of object creation. If a class has a
constructor then whenever an object of that class is created, the constructor is
called.

2. PHP Destructor:-
PHP Destructor method is called just before PHP is about to release any object
from its memory. Generally, you can close files, clean up resources etc in the
destructor method. Let's take an example,
<?php
class Person {
// first name of person
private $fname;
// last name of person
private $lname;
// Constructor
public function __construct($fname, $lname) {
echo "Initialising the object...<br/>";
$this->fname = $fname;
$this->lname = $lname; no need to explicitly call a
} destructor as it will be
// Destructor automatically called once
public function __destruct(){ all program ends its
// clean up resources or do something else execution and same with
echo "Destroying Object..."; construct as class name
} is used to pass
parameters when we
// public method to show name
declare a construct
public function showName() {
echo "The Legend of India: " . $this->fname . " " . $this->lname . "<br/>";
}}
// creating class object
$j = new Person("Swami", "Vivekananda");
$j->showName();
?>

Unit III
Apply Object Oriented Concepts in PHP Page 8
<?php <?php

class car{ class car{

public $name; public $name;


public $type; public $type;

function __construct($name,$type){ function __construct($name,$type){


$this->name=$name; $this->name=$name;
$this->type=$type; $this->type=$type;
} }

function getName(){
return $this->name; function __destruct(){}
}
function getType(){ }
return $this->type;
} $honda = new car("hero honda","EV");
function __destruct(){}
} $mycarName=$honda->name;
$mycarType=$honda->type;
echo "Name of car is : ".$mycarName;
$honda = new car("hero honda","EV"); echo "</br> Type of car is: ".$mycarType;
echo "Name of car is : ".$honda->getName();
echo "</br> Type of car is: ".$honda->getType();

?>

We can use both ways to display


information either create get function and
return value or create a variable and then
assign it the property as we cant directly
print property using echo as echo can onl
print string either we return the property by
creating class method or createa variable
which stores property value as string

we created separate variable and store the property


value as string , as its a variable we have to use $
symbol but there is no need of using $ sign for
property or method outside the class when we call or
refer to property or method of the object of that class
and when u are inside th eclass and u want to refer
the property u refer it with $this->property
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

Output:
Initialising the object...
The Legend of India: Swami Vivekananda
Destroying Object...

 As we can see in the output above, as the PHP program ends, just before it
PHP initiates the release of the object created, and hence the destructor method
is called.
 The destructor method cannot accept any argument and is called just before
the object is deleted, which happens either when no reference exist for an
object or when the PHP script finishes its execution.

3.3 1. Inheritance

PHP - What is Inheritance?


 Inheritance in OOP = When a class derives from another class.The child
class will inherit all the public and protected properties and methods from
the parent class.
 In addition, it can have its own properties and methods.An inherited class is
defined by using the extends keyword.
 Syntax for Inheriting a Class-
In PHP, extends keyword is used to specify the name of the parent class
while defining the child class.
 For example,
<?php
class Parent {
// parent class code
}
class Child1 extends Parent {
// child class code
}
class Child2 extends Parent {
// child class code
}
?>

Some important points to remember while using inheritance are:


 Child class can access and use only the non-private properties and methods
on the parent class.
 Child class can have it's own methods too, which will not be available to
the parent class.
 Child class can also override a method defined in the parent class and
provide its own implementation for it.

Unit III
Apply Object Oriented Concepts in PHP Page 9
<?php

class student{

public $name;
public $branch;

function __construct($name,$branch){
$this->name=$name;
$this->branch=$branch;
}

public function parentmsg(){


echo "hello im from parent class student accesseed by object of class student accessed by
objectof child class </br>";
}
function __destruct(){}

class user1 extends student{


public function childmsg(){
echo "Im $this->name from $this->branch branch and this my childmsg() function accesseed by
child object i inherited these name and branch property from my parent class student as i extends class
student ";
}
}

$stu1 = new user1("tejas","CSE");


$stu1->parentmsg(); // accessing method of parent class using object of child class
$stu1->childmsg();
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 Example
<?php
class car {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The car is {$this->name} and the color is {$this-
>color}.<br>";
}
}
class maruti extends car {
public function message() {
echo " Maruti in an Indian company of car<br>";
}
}
$d = new maruti("swift dzire", "red");
$d->message();
$d->intro();
?>

Output:
Maruti in an Indian company of car
The car is swift dzire and the color is red.

 The maruti class is inherited from the car class.This means that the maruti
class can use the public $name and $color properties as well as the public
__construct() and intro() methods from the car class because of inheritance.
The maruti class also has its own method: message().

2. Overloading
1. Function overloading or method overloading is the ability to create
multiple functions of the same name with different implementations
depending on the type of their arguments.
2. Overloading in PHP provides means to dynamically create properties and
methods.
3. These dynamic entities are processed via magic methods, one can
establish in a class for various action types.
4. The overloading methods are invoked when interacting with properties or
methods that have not been declared or are not visible in the current scope
5. All overloading methods must be defined as Public. After creating an

Unit III
Apply Object Oriented Concepts in PHP Page 10
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

object for a class, we can access a set of entities that are properties or
methods not defined within the scope of the class.
6. Such entities are said to be overloaded properties or methods, and the
process is called overloading.
7. For working with these overloaded properties or functions, PHP magic
methods are used.
8. Most of the magic methods will be triggered in object context except
__call() method which is used in dynamic context.
9. __call() and __callStatic() are called when somebody is calling a
nonexistent object method in object or static context. public __call ( string
$name , array $arguments ) : mixed public static __callStatic ( string
$name , array $arguments ) : mixed
10. __call() is triggered when invoking inaccessible methods in an object
context. __callStatic() is triggered when invoking inaccessible methods in
a static context.
11. The $name argument is the name of the method being called. The
$arguments argument is an enumerated array containing the parameters
passed to the $name'ed method.

Example - Overloading methods via the __call()


<?php
class Shape {

function __call($name,$arg){
if($name == 'area')
switch(count($arg)){
case 0 : return 0 ;
case 1 : return 3.14 * $arg[0]**2 ;
case 2 : return $arg[0] * $arg[1];
}
}
}
$circle = new Shape();
echo "Function without parameters retun ".$circle->area()."<br>";
echo "Area of circle=".$circle->area(3)."<br>";
echo "Area of rectangle=".$circle->area(8,6);
?>

Output:
Function without parameters retun 0
Area of circle=28.26
Area of rectangle=48

Unit III
Apply Object Oriented Concepts in PHP Page 11
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

3.
Overriding
1. It is the same as other OOPs programming languages.
2. In this function, both parent and child classes should have the same
function name and number of arguments.
3. It is used to replace the parent method in child class.
4. The purpose of function overriding is to change the behavior of the parent
class method.
5. The two functions with the same name and the same parameter are called
function overriding.

Example
<?php
class aicte {
function helloWorld() {
echo "Parent"."<br>";
}
}
class msbte extends aicte {
function helloWorld() {
echo "\nChild";
}
}
$p = new aicte;
$c= new msbte;
$p->helloWorld();
$c->helloWorld();
?>

Output:
Parent
Child
4.
Cloning Object
1. The clone keyword is used to create a copy of an object.
2. If any of the properties was a reference to another variable or object, then
only the reference is copied.
3. Objects are always passed by reference, so if the original object has
another object in its properties, the copy will point to the same object.
4. This behavior can be changed by creating a __clone() method in the class.
5. The clone keyword allows you to perform a shallow copy of an object.
6. By combining the clone keyword and __clone() magic method, you can
perform a deep copy of an object.

Unit III
Apply Object Oriented Concepts in PHP Page 12
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

Copying object via assignment

<pre>
<?php
class class1{
public $name; Output:
public $ref_class2;
function setname($n) After change:
{ class1 Object
$this->name=$n; (
} [name] => ABC
} [ref_class2] => class2 Object
class class2{ (
public $roll_no; [roll_no] => 10
public $std; [std] => TYCO
function set_detail($r,$s)
)
{
$this->roll_no=$r;
)
$this->std=$s;
clone object
}
class1 Object
}
(
$c1=new class1();
$c1->name="XYZ"; [name] => ABC
$c1->ref_class2=new class2(); [ref_class2] => class2 Object
$c1->ref_class2->roll_no=50; (
$c1->ref_class2->std="SYCO"; [roll_no] => 10
$c2=$c1; [std] => TYCO
$c1->setname("ABC"); )
$c1->ref_class2->set_detail(10,"TYCO");
echo"After change:<br>"; )
print_r($c1);
echo"clone object<br>";
print_r($c2);
?>
</pre>

In this example, both $c1 and $c2 reference the same object in the memory. When
we change the property of an object, it reflects in both references.
C1
$name: XYZ $roll_no: 10
$ref_class2: ref $std: TYCO
C2

Unit III
Apply Object Oriented Concepts in PHP Page 13
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

Copying object using the clone keyword

PHP provides you with the clone keyword that allows you to create a shallow
copy of an object. For example:

<pre>
<?php Output:
class class1{
public $name; After change:
public $ref_class2;
class1 Object
function setname($n)
(
{
[name] => ABC
$this->name=$n;
[ref_class2] => class2 Object
}
(
}
[roll_no] => 10
class class2{
public $roll_no; [std] => TYCO
public $std; )
function set_detail($r,$s)
{ )
$this->roll_no=$r; clone object
$this->std=$s; class1 Object
} (
} [name] => XYZ
$c1=new class1(); [ref_class2] => class2 Object
$c1->name="XYZ"; (
$c1->ref_class2=new class2(); [roll_no] => 10
$c1->ref_class2->roll_no=50; [std] => TYCO
$c1->ref_class2->std="SYCO"; )
$c2=clone $c1;
$c1->setname("ABC"); )
$c1->ref_class2-
>set_detail(10,"TYCO");
echo"After change:<br>";
print_r($c1);
echo"clone object<br>";
print_r($c2);
?> $name: ABC
</pre> C1 $ref_class2: ref
$roll_no: 10
$std: TYCO
C2 $name: XYZ
$ref_class2: ref

Unit III
Apply Object Oriented Concepts in PHP Page 14
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

PHP __clone magic method

 The __clone() is a magic method with the following syntax:


function __clone ( ) : void
 If you define the clone() method, PHP will execute it automatically when the
cloning completes. The clone() is useful when you want to change the
properties of the copied object.
 After shallow copy when an object has a property that references another
object, that property remains a reference after cloning(as seen in the above
example).
 Deep copy creates a copy of an object and recursively creates a copy of the
objects referenced by the properties of the object.
 Since PHP calls the __clone() method automatically after cloning an object,
you can clone the objects referenced by the properties of the class.
<pre>
<?php After change:
class class1{
class1 Object
public $name;
public $ref_class2; (
function __clone() [name] => ABC
{ [ref_class2] => class2 Object
$this->ref_class2=clone $this->ref_class2; (
} [roll_no] => 10
function setname($n) [std] => TYCO
{
)
$this->name=$n;
}
} )
class class2{ clone object
public $roll_no; class1 Object
public $std; (
function set_detail($r,$s)
[name] => XYZ
{
[ref_class2] => class2 Object
$this->roll_no=$r;
$this->std=$s; (
} [roll_no] => 50
} [std] => SYCO
$c1=new class1(); )
$c1->name="XYZ";
$c1->ref_class2=new class2();
)
$c1->ref_class2->roll_no=50;
$c1->ref_class2->std="SYCO";
$c2=clone $c1;
$c1->setname("ABC");
$c1->ref_class2->set_detail(10,"TYCO");
echo"After change:<br>";
print_r($c1);

Unit III
Apply Object Oriented Concepts in PHP Page 15
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

echo"clone object<br>";
print_r($c2);
?>
</pre>

$name: ABC $roll_no: 10


C1
$ref_class2: ref $std: TYCO

C2
$name: XYZ $roll_no: 10
$ref_class2: ref $std: TYCO

3.4 1. Introspection
Introspection is the ability of a program to examine an object characteristics such
as its name, parent class, properties and method.

Introspection allow us to:


 Obtain the name of the class to which an object belongs as well as its member
properties and method
 write generic debuggers, serializers, profilers
 Introspection in PHP offers the useful ability to examine classes, interfaces,
properties and method with introspection we can write code that operates on
any class or object
 To examining classes the introspective function provided by PHP are
class_exits(), get_class_method(), get_class_vars() etc.

(i) class_exists():
 This function is used to determine whether a class exists.It takes a string
and return a Boolean value.
 Syntax-
$yes_no=class_exists(classname);
 This function returns TRUE if classname is a defined class, or FALSE

(ii) get_class_method()
 This function returns the names of the class methods.

(iii) get_parent_class():
 return the class name of an object parent class

(iv) is_subclass_of():
 The is_subclass_of() function returns TRUE if the object “object” belongs
to a class which is a subclass of “class”, FALSE otherwise.
 Syntax
 is_subclass_of(object, class, string)

Unit III
Apply Object Oriented Concepts in PHP Page 16
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

<?php
if(class_exists('parent'))
{
$ob=new parent();
echo "This is parent class";
}
else
{
echo "Not exist";
}
?>

output:
Not exist

<?php
class TYCO
{
function a()
{
echo "hey CO6I";
}}
if(class_exists('TYCO'))
{
$ob=new TYCO();
echo "This is TYCO class…";
echo "<br>";
echo $ob->a();
}
else
{
echo "Not exist";
}
?>
Output:
This is TYCO class…
hey CO6I

Unit III
Apply Object Oriented Concepts in PHP Page 17
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

<pre>
<?php

class Rectangle
{
var $dim1 = 2;
var $dim2 = 10;

function Rectangle1($dim1,$dim2)
{
$this->dim1 = $dim1;
$this->dim2 = $dim2;
}
}

class area extends Rectangle{


function area1()
{
return $this->dim1*$this->dim2;
}

function display()
{
echo"This is child class display";
}
}
$a = new area(4,2);
echo"get the class varibale i.e properties<br>";
$class_properties = get_class_vars("Rectangle");
print_r($class_properties);

echo"get object properties<br>";


$object_properties = get_object_vars($a);
print_r($object_properties);

echo"get class methods<br>";


$class_method1 = get_class_methods("Rectangle");
$class_method2 = get_class_methods("area");
print_r($class_method1);
print_r($class_method2);

echo"get class corresponding to an object<br>";


$object_class = get_class($a);
print_r($object_class);

echo "<br>get parent class<br>";


Unit III
Apply Object Oriented Concepts in PHP Page 18
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

$parent=get_parent_class(area);
print_r($parent);

echo "<br>check object has parent class or not<br>";


$child1=is_subclass_of($a,Rectangle);
print_r($child1);
?>
</pre>

Output:

get the class varibale i.e properties


Array
(
[dim1] => 2
[dim2] => 10
)
get object properties
Array
(
[dim1] => 2
[dim2] => 10
)
get class methods
Array
(
[0] => Rectangle1
)
Array
(
[0] => area1
[1] => display
[2] => Rectangle1
)
get class corresponding to an object
area
get parent class
Rectangle
check object has parent class or not
1

Unit III
Apply Object Oriented Concepts in PHP Page 19
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

2.
serialize
 The serialize() function converts a storable representation of a value.
 Syntax
serialize(value);
 To serialize data means to convert a value to a sequence of bits, so that it
can be stored in a file, a memory buffer, or transmitted across a network.
<?php
Example
// Complex array
$myvar = array(
'hello',
42,
array(1, 'two'),
'apple'
);
// Convert to a string
$string = serialize($myvar);
// Printing the serialized data
echo $string;
?>
 Output:
a:4:{i:0;s:5:"hello";i:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3:"two";}i:3;s:5:"apple";}

3.
Unserialize()
 The unserialize() is an inbuilt function php that is used to unserialize the
given serialized array to get back to the original value of the complex array,
$myvar.
 Syntax:
unserialize( $serialized_array )
 Below program illustrate both serialize() and unserialize() functions:
Program:
<?php
// Complex array
$myvar = array(
'hello',
42,
array(1, 'two'),
'apple'
);
// Serialize the above data
$string = serialize($myvar);
// Unserializing the data in $string
$newvar = unserialize($string);
// Printing the unserialized data
print_r($newvar);
Unit III
Apply Object Oriented Concepts in PHP Page 20
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

?>
Output:
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)
[3] => apple
)

Unit III
Apply Object Oriented Concepts in PHP Page 21
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

4.1  Creating a webpage using GUI Components


 Browser Role
 GET and POST Method
 Server Role

4.2 Form Controls


 Text area
 Text Box
 Radio Button
 Check Box
 List
 Buttons

4.3 Working with multiple forms:


 A web page having many forms
 A form having multiple submit buttons

4.4 Web page validation

4.5 Cookies :
 Use of cookies
 Attributes of cookies
 Create cookies
 Modify Cookies value
 Delete cookies

4.6 Session:
 Use of session
 Start session
 Get session variables
 Destroy session

4.7 Sending E-mail

Unit IV
Creating and Validating Forms 1
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

4.1 Introduction to Webpage


 To run any code on server or to get connected with PHP on server we need to set up
Web pages in a specific fashion.
 Two methods “get” and “post” mentioned in form are commonly used to send data
from HTML controls to PHP scripts on the server.
 URL is used to specify location, which helps browsers understand where to send
the data on the server mentioned in the “action: attribute of a form”.
 PHP script handles both displaying of HTML controls and then reading of data
from HTML controls when the user clicks on the submit button.

1. Creating a Webpage using GUI components


 A document that contains blank fields, that the user can fill the data or user ca
select the data is known as form.Generally the data will be stored in the database.
 We can create and use forms in PHP. To get form data, we need to use PHP
superglobals. $_GET and $_POST.
 The form request may be get or post. To retrieve data from get request we need to
use $_GET, for post request $_POST.
2. Browser Role - GET and POST Methods
Browser used one of the two HTTP methods - GET and POST to communicate with the
server. Both methods are used to pass the information differently to the server.

i. GET method:
1. The GET method sends the encoded user information appended to the page
request (to the url). The code and the encoded information are separated by the ?
character.
2. http://www.test.com/index.htm?name1=value1&name2=value2
3. The GET method produces a long string that appears in our server logs, in th
browser’s location:box.
4. Never use the GET method if we have a password or other sensitive information
to be sent to the server. Get cannot be used to send binary data, like images or
word documents, to the server.
5. The data sent by the GET method can be accessed using the QUESRY_STRING
environment variable.
6. PHP provides a $_GET associative array to access all the sent information using
the GET method.

Unit IV
Creating and Validating Forms 2
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

ii POST Method
1. The POST method transfers information via HTTP headers. The information is
encoded as described in the case of the GET method and put into a header called
QUERY_STRING.
2. The POST method does not have any restriction on data size to be sent.
3. The POST method can be used to send ASCII as well as binary data.
4. The data sent by POST method goes through HTTP header so security depends
on HTTP protocol. By using Secure HTTP you can make sure that your
information is secure.
5. The PHP provides a $_POST associative array to access all the sent information
using the POST method.

Difference between get and post

GET Method
1. Information sent from a form with the get method is visible to everyone(all variable
names and values are displayed in the URL)
2. GET has limits on the amount of information to send. The limitation is about 2048
characters.
3. $_GET is an array of variables passed to the current script via the URL parameters.
4. Can be bookmarked.
5. Can be cached.
6. Parameters remain in browser history.

POST Method
1. 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)
2. Post has no limits on the amount of information to send.
3. $_POST is an array of variables passed to the current script via the HTTP POST
method.
4. Cannot be bookmarked.
5. Not cached.
6. Parameters are not saved in browser history.
3. Server Role
1. Role of PHP in Web Applications.
2. PHP is a server side scripting language. That means its processing happens in the
server by consuming server's resources and sends only the output to the client.
3. In a client side scripting language like JavaScript, processing happens in the client's
compute Consuming its resources.

Unit IV
Creating and Validating Forms 3
See after this u will come across something like

$_POST
$_GET
$_SERVER
$_COOKIE

All of this are called super-globals I.e can access data


globally

These take paramaters in square brackets [] so don’t


confuse these with function functions will be normal
they don’t require $ symbol , now u will not get
confused, also superglobals have single underscore _
. don’t confuse superglobals with magic functions
like
__get() these are totally different from each other

eg. superglobal
$_COOKIE[“name”] ;
// returns the value of cookie who’s name is specified

Function

isset() ; // used to check if value of paramaeter


passed is set or not
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

4.2 Form controls


1 Textbox
 A text input field allows the user to enter a single line of text.
 Textbox field enable the user to input text information to be used by the program
 The text field can be set using
<input type=“text” size=“30” name=“user” value=“ “
 Step1:
create a form in some HTML file as follows-
Input.html
<form action="hello.php" method="get">
Name:<input type="text" name="user"/>
<input type="submit" value="Submit"/>
</form>
 Step 2:
Now the hello.php program can be as follows-
<?php
$name=$_GET["user"];
echo"Hello,$name";
?>
 step3

 Step 4

2. Textarea

Unit IV
Creating and Validating Forms 4
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 A text area field is similar to a text input field but it allows the user to enter
multiple line of text.
 Syntax
<textarea name=name of component row=“some number”cols=“some number”><
/textarea>
 Eg<textarea name=”address” rows=“5” cols=“40”>< /textarea>
3.
Checkbox
 <form action="#" method="post">
<input type="checkbox" name="gender" value="Male">Male</input>
<input type="checkbox" name="gender" value="Female">Female</input>
<input type="submit" name="submit" value="Submit"/>
</form>

 <?php
if (isset($_POST['gender'])){
echo $_POST['gender']; // Displays value of checked checkbox.
} ?>

 To get value of multiple checked checkboxes,


<form action="#" method="post">
<input type="checkbox"
name="check_list[]"value="C/C++"><label>C/C++</label><br/>
<input
type="checkbox"name="check_list[]"value="Java"><label>Java</label><br/>
<input type="checkbox"
name="check_list[]"value="PHP"><label>PHP</label><br/>
<input type="submit" name="submit" value="Submit"/>
</form>

<?php
if(isset($_POST['submit']))
{//to run PHP script on submit
if(!empty($_POST['check_list']))
{
// Loop to store and display values of individual checked checkboxes.
foreach($_POST['check_list'] as $selected){
echo $selected."</br>";
}
}
}
?>

4. List Box

Unit IV
Creating and Validating Forms 5
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

 <html>
<body>
<div>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<label> Best Engineering College in Maharashtra</label>
<p><select name="products[]" multiple="multiple">
<option>VESIT</option>
<option>VJTI</option>
<option>COEP</option>
<option>PCIT</option>
<option>IIT</option>
<option>AVCOE</option>
<option>DY Patil</option>
<option>BATU</option>
</select></p>
<p><input type="submit" value="Test me!" /></p>
</form>
</div></body></html>

 <?php
if (is_array ( $_POST ['products'] )) {
print "<p>Your product choices are:</p>";
print "<ul>";
foreach ( $_POST ['products'] as $value ) {
print "<li>$value</li>\n";
}
print "</ul>";
}?>

4.3 Working with multiple forms:

 A web page having multiple forms It can be processed in two steps:


1. Posting each form to a different PHP script file for processing Multiple
functionality can be provided in a single web page by providing multiple forms
in a web page having different functionality.
2. Each form on this web page will be given a separate name that will uniquely
identify the form in the web page with multiple forms.
 Data from each form should be given to a separate PHP script file for processing by
specifying PHP script filename in the action attribute of the form.
 Each PHP script should be written in such a fashion that will handle all the data
coming from the form.

1. Disadvantage - we have to write separate files for each form.


A web page having many forms
Unit IV
Creating and Validating Forms 6
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

<form method="post">
<h3>personal information form</h3>
user name:<input type="text" name="username"/>
<br/><br/>
address:<input type="text" name="address"/>
<br/><br/>
<input type="submit" name="submit_personal_info" value="submit"/>
<br/>
</form>
<form method="post">
<h3>Feedback Form</h3>
<textarea name="feedback" rows="5" cols="50"></textarea>
<br/>
<input type="submit" name="submit_feedback"/>
</form>
<?php
if(!empty($_POST['submit_personal_info']))
{
echo "<h3>welcome user:".$_POST['username']."</h3>";
}
if(!empty($_POST['submit_feedback']))
{
echo "<h3>we value your feedback:</h3>";
echo "your feedback is<br/>".$_POST["feedback"];
}
?>
2.
A form having multiple submit buttons.
<form method="post">
<h3>Simple Arithmetic Calculator</h3>
Number 1: <input type="text" size="5" name="num1"/>
<br/><br>
Number 2: <input type="text" size="5" name="num2"/>
<br/><br>
<input type="submit" name="add" value="ADDITION"/>
<input type="submit" name="sub" value="SUBTRACTION"/>
<input type="submit" name="mul" value="MULTIPLICATION"/>
<input type="submit" name="div" value="DIVISION"/>
<?PHP
if(!empty($_POST['add'])) {
$result=$_POST['num1']+$_POST['num2'];
echo "<h3> Addition: ".$result."</h3>";
}
if(!empty($_POST['sub']))

Unit IV
Creating and Validating Forms 7
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

{
$result=$_POST['num1']-$_POST['num2'];
echo "<h3> Subtraction: ".$result."</h3>";
}
if(!empty($_POST['mul']))
{
$result=$_POST['num1']*$_POST['num2'];
echo "<h3> Multiplication: ".$result."</h3>";
}
if(!empty($_POST['div']))
{
$result=$_POST['num1']/$_POST['num2'];
echo "<h3> Division: ".$result."</h3>";
}
?>

4.4 Web Page Validation


What is Validation ?
 Required field will check whether the field is filled or not in the proper way
Most of cases we will use the * symbol for required field.
 Validation means checking the input submitted by the user. There are two types
of validation available in PHP. They are as follows −
 Client-Side Validation –
Validation is performed on the client machine web browsers.
 Server Side Validation –
After submitted by data, The data is sent to a server and performs validation
checks in the server machine.

Some of Validation rules for field

Unit IV
Creating and Validating Forms 8
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

Example of validation
Use this
1. filter_var()
Valid URL
 Below code shows validation of URL
function instead
$weburl = input($_POST["sitename"]); of regex :)
if(filter_var($weburl,FILTER_VALIDATE_URL)){
echo “valid url”;
}
else{
echo “invalid url”;
}

Above syntax will verify whether a given URL is valid or not. It should allow
some keywords as https, ftp, www, a-z, 0-9,..etc..

2.
Valid Email
 Below code shows validation of Email address
<?php

$emailid = "tejasnarwadegmail.com";

if(filter_var($emailid , FILTER_VALIDATE_EMAIL)){ echo "valid email";



}else{ echo "invalid email";}

?>
Predefined function for validation in php are given below:

i) The filter_input() function gets an external variable (e.g. from form input) and
optionally filters it. This function is used to validate variables from insecure sources,
such as user input.
Syntax
filter_input(type, variable, filter)
type Required. The input type to check for. Can be one of the following:
INPUT_GET
INPUT_POST
INPUT_COOKIE
Unit IV
Creating and Validating Forms 9
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

INPUT_SERVER
INPUT_ENV
variable Required. The variable name to check
filter Optional. Specifies the ID or name of the filter to use. Default is
FILTER_DEFAULT, which results in no filtering
Program:
<?php
if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL)) {
echo("Email is not valid");
} else {
echo("Email is valid");
}
?>
ii) The filter_var() function filters a variable with the specified filter.
Syntax
filter_var(var, filtername)
Program:
<?php
$email = "[email protected]";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
?>

2.5
Cookie
1. Cookie is a small piece of information stored as a file in the user's browser by the
web server.
2. Once created, cookie is sent to the web server as header information with every
HTTP request.
3. You can use cookies to save any data but it should not exceed 1K(1024 bytes) in
size.
4. Before we move on to how to create, update and delete cookies, let's learn a few real
world uses of cookies.

Unit IV
Creating and Validating Forms
10
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

Here,
1) A user requests for a page that stores cookies
2) The server sets the cookie on the user’s computer
3) Other page requests from the user will return the cookie name and value

1.
Why and when to use Cookies?

 Http is a stateless protocol; cookies allow us to track the state of the application
using small files stored on the user’s computer. The path where the cookies are
stored depends on the browser. Internet Explorer usually stores them in the
Temporary Internet Files folder.
 Personalizing the user experience – this is achieved by allowing users to select their
preferences. The page requested that follows are personalized based on the set
preferences in the cookies.
 Tracking the pages visited by a user
 To store user information like when he/she visited, what pages were visited on the
website etc, so that next time the user visits your website you can provide a better
user experience.
 To store basic website specific information to know this is not the first visit of
user.
 You can use cookies to store the number of visits or view counters.
 I hope this gives you an idea about how you can utilize cookies in your web
application.

2.
Types of Cookies
There are two types of cookies, they are:
1. Session Cookie:
This type of cookies are temporary and expire as soon as the session ends or the
browser is closed.
2. Persistent Cookie:
To make a cookie persistent we must provide it with an expiration time. Then
the cookie will only expire after the given expiration time, until then it will be a
valid cookie.
3. You can use cookies to store number of visits or view counter.

3. Creating a Cookie in PHP


 In PHP we can create/set a cookie using the setcookie() function.
 Syntax for the function,
setcookie(name, value, expire, path, domain, secure)
 The first argument which defines the name of the cookie is mandatory, rest all are
optional arguments.

Unit IV
Creating and Validating Forms
11
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

Example
So if we want to create a cookie to store the name of the user who visited your website,
and set an expiration time of a week, then we can do it like this,

<?php
setcookie("username", "Shika", time()+60*60*24*7);
?>
 To access a stored cookie we use the $_COOKIE global variable, and can use the
isset() methods to check whether the cookie is set or not.
 Let's have a complete example where we will set a cookie and then retrieve it t
show its value in the HTML page.
<?php
// set the cookie
setcookie("username", "Ramkra", time()+60*60*24*7);
Unit IV
Creating and Validating Forms
12
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

?>
<html>
<body>
<?php
// check if the cookie exists
if(isset($_COOKIE["username"]))
{
echo "Cookie set with value: ".$_COOKIE["username"];
}
else
{
echo "cookie not set!";
}
?>
</body>
</html>
 So by providing the name of the cookie inside the square brackets with the global
variable $_COOKIE[] we can access the cookie.
 setcookie() function must be placed before the starting HTML tag(<html>).

4.
Updating Cookie in PHP
 To update/modify a cookie, simply set it again. For example, if we want to update
the username
 stored in the cookie created above, we can do it using setcookie() method again,
<?php
// updating the cookie
setcookie("username", "Ambarish", time()+60*60*24*7);
?>
<html>
<body>
<?php
// check if the cookie exists
if(isset($_COOKIE["username"]))
{
echo "Cookie set with value: ".$_COOKIE["username"];
}
else
{
echo "cookie not set!";
}
?>
</body>
</html>
 We just update the value of the username cookie.

Unit IV
Creating and Validating Forms
13
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

5.
Delete a Cookie in PHP
 To delete/remove a cookie, we need to expire the cookie, which can be done b
updating the cookie using the setcookie() function with expiration date in past.
<?php
// updating the cookie
setcookie("username", "Dhruv", time() - 3600);
?>
<html>
<body>
<?php
echo "cookie username is deleted!";
?>
</body>
</html>
 And with this, we now know how to create a cookie, how to update it and how to
delete it when we no longer need it.

2.6 Session
1. A session is a way to store information (in variables) to be used across multiple
pages. Unlike a cookie, the information is not stored on the user's computer.
2. When you work with an application, you open it, do some changes, and then you
close it. This is much like a Session.
3. The computer knows who you are. It knows when you start the application and
when you end. But on the internet there is one problem: the web server does not
know who you are or what you do, because the HTTP address doesn't maintain
state.
4. Session variables solve this problem by storing user information to be used across
multiple pages (e.g. username, favorite color, etc). By default, session variables
last until the user closes the browser.
5. So Session variables hold information about one single user, and are available to
all pages in one application.
6. If you need permanent storage, you may want to store the data in a database.
1.
Start a PHP Session
 A session is started with the session_start() function.
 Session variables are set with the PHP global variable: $_SESSION.
 Now, let's create a new page called "demo_session1.php". In this page, we start a
new PHP session and set some session variables.
 ExampleGet your own PHP Server
<?php
// Start the session
session_start();
?>
Unit IV
Creating and Validating Forms
14
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>
 The session_start() function must be the very first thing in your document. Before
any HTML tags.

2. Get PHP Session Variable Values


 Next, we create another page called "demo_session2.php". From this page, we will
access the session information we set on the first page ("demo_session1.php").
 Notice that session variables are not passed individually to each new page, instead
they are retrieved from the session we open at the beginning of each page
(session_start()).
 Also notice that all session variable values are stored in the global $_SESSION
variable:
 Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
3.
Modify a PHP Session Variable
 To change a session variable, just overwrite it:
 Example
<?php
session_start();
Unit IV
Creating and Validating Forms
15
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

?>
<!DOCTYPE html>
<html>
<body>

<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>

</body>
</html>
4.
Destroy a PHP Session
 To remove all global session variables and destroy the session, use session_unset()
and session_destroy().
 Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();

// destroy the session


session_destroy();
?>

</body>
</html>

4.7
Sending E-mail
 PHP mail is the built-in PHP function that is used to send emails from PHP scripts.
 The mail function accepts the following parameters;
1. Email address
2. Subject
3. Message
4. CC or BCC email addresses

Unit IV
Creating and Validating Forms
16
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

Use of Mail()
1. It’s a cost effective way of notifying users on important events.
2. Let users contact you via email by providing a contact us form on the website that
emails the provided content.
3. Developers can use it to receive system errors by email
4. You can use it to email your newsletter subscribers.
5. You can use it to send password reset links to users who forget their passwords
6. You can use it to email activation/confirmation links.
7. This is useful when registering users and verifying their email addresses Sending
mail using PHP.

The PHP mail function has the following basic syntax


<?php
mail($to_email_address,$subject,$message,[$headers],[$parameters]);
?>

HERE,
 “$to_email_address” is the email address of the mail recipient
 “$subject” is the email subject
 “$message” is the message to be sent.
 “[$headers]” is optional, it can be used to include information such as CC, BCC
 CC is the acronym for carbon copy. It’s used when you want to send a copy to
an interested
 person i.e. a complaint email sent to a company can also be sent as CC to the
complaints board.
 BCC is the acronym for blind carbon copy. It is similar to CC. The email
addresses included in the
 BCC section will not be shown to the other recipients.

Simple Mail Transmission Protocol (SMTP)


 PHP mailer uses Simple Mail Transmission Protocol (SMTP) to send mail.On a
hosted server, the SMTP settings would have already been set.The SMTP mail
settings can be configured from “php.ini” & “sendemail.ini “ file in the PHP
installation folder.

1. File :-Php.ini
//email function
smtp_port=465
sendmail_from = [email protected]
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
mail.add_x_header=on

2. File:- sendemail.ini
smtp_server=smtp.gmail.com
smtp_port=465

Unit IV
Creating and Validating Forms
17
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

smtp_ssl=auto
error_logfile=error.log
[email protected]
auth_password=
1.Configure SMTP settings on your localhost Assuming you are using xampp on
windows, locate the “php.ini” in the directory “C:\xampp\php”.

● Open it using a notepad or any text editor. We will use a notepad in this example.
Click
on the edit menu

Unit IV
Creating and Validating Forms
18
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

Locate the entries


○ [mail function]
○ ; XAMPP: Don’t remove the semicolon if you want to work with an SMTP Server
like Mercury
○ ; SMTP = localhost
○ ; smtp_port = 25
○ Remove the semi-colons before SMTP and smtp_port and set the SMTP to your
smtp server and the port to your smtp port. Your settings should look as follows
■ SMTP = smtp.example.com
■ smtp_port = 25
■ Note the SMTP settings can be gotten from your web hosting providers.
■ If the server requires authentication, then add the following lines.
■ auth_username = [email protected]
■ auth_password = example_password
■ Save the new changes.
■ Restart Apache server.

Php Mail Example


<?php
$to_email = 'name @ company . com';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail function';
$headers = 'From: noreply @ company . com';
mail($to_email,$subject,$message,$headers);
?>

Unit IV
Creating and Validating Forms
19
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

Unit IV
Creating and Validating Forms
20
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

5.1 Introduction to MySQL-


Create a database

5.2 Connecting to MySQL database-


MySQL database server from PHP

5.3 Database Operations-


Insert data
Retrieving the query result

5.4 Update and delete oprations on table

Unit V
Database Operations Page 1
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

2.1 1. Introduction to MySQL- create a 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

1.Create database
<?php
$servername = "localhost";
$username = "root";
$password = "";/* Put your password here*/
/* Create connection*/
$conn = mysqli_connect($servername, $username, $password);
/* Check connection*/
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
/* Create database*/
$sql = "CREATE DATABASE stud";
if (mysqli_query($conn, $sql)) {
echo " $sql created successfully";
}else{
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>

mysqli_connect(host, username, password, dbname, port, socket)

Parameter Description
1. host Optional. Specifies a host name or an IP address
2. username Optional. Specifies the MySQL username
3. password Optional. Specifies the MySQL password
4. dbname Optional. Specifies the default database to be used

Unit V
Database Operations Page 2
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

5. port Optional. Specifies the port number to attempt to connect to the


MySQL server
6. socket Optional. Specifies the socket or named pipe to be used

The die():-
It is an inbuilt function in PHP. It is used to print message and exit from the
current php script. It is equivalent to the exit() function in PHP.

Syntax :
die($message)

Parameters :
This function accepts only one parameter and which is not mandatory to be
passed.

$message :
This parameter represents the message to be printed while exiting from script.

5.2 Connection to a Mysql database

PHP will work with virtually all database software,including oracle and sybase
but most commonly used is freely available MYSQL database php 5 and later can
work with MYSQL database using:
1. MYSQLi extension(“the “i” stands for improved”),and
2. PDO(php data objects)

Should I Use MySQLi or PDO?


 Both MySQLi and PDO have their advantages:
 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 are object-oriented, but MySQLi also offers a procedural API.
 Both support Prepared Statements. Prepared Statements protect from SQL
injection, and are very important for web application security.

There are three ways of working with MySQl and PHP


1. MySQLi (object-oriented)
2. MySQLi (procedural)
3. PDO

Unit V
Database Operations Page 3
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

1. Connecting to MySQL database using PHP

There are 3 ways in which we can connect to MySQl from PHP as listed above
and described below:

1. Using MySQLi object-oriented procedure:


We can use the MySQLi object-oriented procedure to establish a connection
to MySQL database from a PHP script.

Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = new mysqli($servername, $username, $password);
// Checking connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Output:
Connected successfully

Explanation:
We can create an instance of the mysqli class providing all the necessary
details required to establish the connection such as host, username, password
etc. If the instance is created successfully then the connection is successful
otherwise there is some error in establishing connection.

2. Using MySQLi procedural procedure :


There is also a procedural approach of MySQLi to establish a connection to
MySQL database from a PHP script as described below.

Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = mysqli_connect($servername, $username, $password);
// Checking connection
if (!$conn) {

Unit V
Database Operations Page 4
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

die("Connection failed: " . mysqli_connect_error());


}
echo "Connected successfully";
?>

Output:
Connected successfully

Explanation:
In MySQLi procedural approach instead of creating an instance we can use
the mysqli_connect() function available in PHP to establish a connection.
This function takes the information as arguments such as host, username ,
password , database name etc. This function returns MySQL link identifier
on successful connection or FALSE when failed to establish a connection.

3. Using PDO procedure:


PDO stands for PHP Data Objects. That is, in this method we connect to the
database using data objects in PHP as described below:

Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB",
$username, $password);
// setting the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>

Output:
Connected successfully

Explanation:
The exception class in PDO is used to handle any problems that may occur in
our database queries. If an exception is thrown within the try{ } block, the
script stops executing and flows directly to the first catch(){ } block.

Unit V
Database Operations Page 5
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

2. Closing A Connection
When we establish a connection to a MySQL database from a PHP script , we
should also disconnect or close the connection when our work is finished. Here
we have described the syntax of closing the connection to a MySQL database in
all 3 methods described above. We have assumed that the reference to the
connection is stored in $conn variable.

1) Using MySQLi object oriented procedure


Syntax
$conn->close();

2) Using MySQLi procedural procedure


Syntax
mysqli_close($conn);

3) Using PDO procedure


Syntax
$conn = null;
2.3 Database operations

1. Insert operation
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "stud";
// Create connection
$conn = mysqli_connect($servername, $username, $password,
$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO co (firstname, lastname, email)
VALUES ('abc', 'xyz', '[email protected]')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>

Unit V
Database Operations Page 6
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

2. Retrieve Data
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "stud";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname,email,reg_date FROM co";
$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"]."-Email:"."
".$row["email"]."-Time"." ".$row["reg_date"]."<br>";
//print_r($row);
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>

3. Update data
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "stud";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "UPDATE co SET lastname='XYZ', firstname='ABC' WHERE
id=3";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";

Unit V
Database Operations Page 7
Mrs. Poonam Amit Kamble Web based Application Development with PHP(22619)

} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>

4. Delete Data.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "stud";
// 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 co WHERE id=2";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>

Unit V
Database Operations Page 8

You might also like