WT Chapter 5
WT Chapter 5
Chapter-05
Server-side Scripting with PHP
Modern websites are no longer limited to displaying static content. Websites such as online
shopping platforms, social media applications, banking systems, and educational portals need to
process user requests, store data, and generate dynamic web pages. This functionality is
achieved through server-side scripting.
Server-side scripting refers to the execution of scripts on the web server before the webpage is
sent to the user's browser. When a user requests a webpage, the server processes the script,
performs the necessary operations such as database access or calculations, and then sends the
resulting HTML page to the client. The user sees only the final output and not the server-side
code.
One of the most widely used server-side scripting languages is PHP, which stands for Hypertext
Preprocessor. PHP is an open-source scripting language specifically designed for web
development. It can be embedded directly into HTML and is easy to learn and use.
PHP is a popular server-side scripting language used for developing dynamic and interactive
web applications. It provides several features that make web development easier and more
efficient.
1. Open Source
PHP is open-source software, which means it is free to use, modify, and distribute. Developers
can use PHP without paying any licensing fees.
2. Platform Independent
PHP can run on different operating systems such as Windows, Linux, Unix, and macOS. A PHP
program developed on one platform can easily run on another platform.
PHP has a simple syntax that is easy for beginners to understand. It can also be embedded
directly within HTML, making web development straightforward.
4. Database Support
PHP supports a wide range of databases, including MySQL, PostgreSQL, SQLite, Oracle, and
Microsoft SQL Server. This makes it suitable for developing database-driven applications.
1
Web Technologies IV SEM BCA
5. Fast Performance
PHP scripts are executed on the server and generally provide fast performance. It can efficiently
handle large numbers of users and web requests.
PHP supports Object-Oriented Programming (OOP), allowing developers to create reusable and
well-structured code using classes and objects.
PHP is widely used because it is open-source, platform independent, easy to learn, supports
databases, offers good performance, supports object-oriented programming, and has strong
community support. These features make PHP a powerful language for developing modern web
applications.
XAMPP is a free software package that provides everything needed to run PHP applications on a
local computer. It includes the Apache Web Server, MySQL Database, PHP Interpreter, and
other useful tools. XAMPP allows developers to test PHP programs locally before deploying them
to a live server.
Visit the official XAMPP website and download the version suitable for your operating system.
2
Web Technologies IV SEM BCA
Apache
MySQL
FileZilla
Tomcat
Mercury
Apache [Running]
[Link]
Congratulations. Your computer is now pretending to be a web server. Humans do enjoy making
one computer act like another computer.
The htdocs folder is the default directory where website files are stored.
Location:
C:\xampp\htdocs
Any PHP file placed inside this folder can be accessed through the browser.
[Link]
<?php
echo "Hello, World!";
?>
3
Web Technologies IV SEM BCA
C:\xampp\htdocs
[Link]
Output:
Hello, World!
The PHP code is executed by the server, and the browser displays only the output.
[Link]
Write:
<?php
$name = "Ramesh";
$course = "Data Science";
Save it in:
C:\xampp\htdocs
Run:
[Link]
Output:
Name: Ramesh
Course: Data Science
4
Web Technologies IV SEM BCA
Apache [Stopped]
C:\xampp
│
├── apache
├── mysql
├── php
└── htdocs
│
├── [Link]
└── [Link]
All PHP files should be placed inside the htdocs folder or its subfolders.
To run PHP programs using XAMPP, first install XAMPP, start the Apache server, create PHP files
inside the htdocs directory, and access them through [Link] XAMPP
provides a simple local development environment for learning and testing PHP applications
without requiring an internet server.
Variables and data types are fundamental concepts in PHP programming. A variable is used to
store data that can be used and modified throughout a program. Data types define the kind of
value that a variable can hold, such as numbers, text, or logical values.
PHP is a loosely typed language, which means that the programmer does not need to explicitly
declare the data type of a variable. PHP automatically determines the data type based on the
value assigned to the variable.
Variables in PHP
A variable is a named storage location used to hold data. In PHP, every variable begins with a
dollar sign ($) followed by the variable name.
Syntax
$variable_name = value;
5
Web Technologies IV SEM BCA
Example
<?php
$name = "Gourav";
$age = 22;
echo $name;
echo "<br>";
echo $age;
?>
Output:
Gourav
22
In this example, $name stores a string value and $age stores an integer value.
Variable Assignment
<?php
$city = "Mysuru";
$population = 1000000;
?>
Here, the value "Mysuru" is assigned to $city, and 1000000 is assigned to $population.
A data type specifies the type of value stored in a variable. PHP supports several built-in data
types.
-> Integer
Example:
<?php
$marks = 85;
echo $marks;
?>
Output:
85
6
Web Technologies IV SEM BCA
Example:
<?php
$price = 99.99;
echo $price;
?>
Output:
99.99
-> String
Example:
<?php
$name = "PHP Programming";
echo $name;
?>
Output:
PHP Programming
-> Boolean
TRUE
FALSE
Example:
<?php
$isStudent = true;
?>
-> Array
Example:
<?php
$colors = array("Red", "Green", "Blue");
echo $colors[0];
7
Web Technologies IV SEM BCA
?>
Output:
Red
-> NULL
Example:
<?php
$subject = NULL;
?>
-> Object
Example:
<?php
class Student {
public $name = "Ravi";
}
Output:
Ravi
PHP provides the var_dump() function to display the value and data type of a variable.
Example:
<?php
$age = 20;
var_dump($age);
?>
Output:
int(20)
8
Web Technologies IV SEM BCA
echo $name;
echo "<br>";
echo $age;
echo "<br>";
echo $percentage;
?>
In this example:
$name is a String.
$age is an Integer.
$percentage is a Float.
$isPassed is a Boolean.
Variables are used to store data in PHP programs, and each variable begins with the $ symbol.
PHP automatically determines the data type of a variable based on the assigned value. Common
data types include Integer, Float, String, Boolean, Array, NULL, and Object. Understanding
variables and data types is essential because they form the foundation of PHP programming and
are used in almost every PHP application.
Operators are special symbols used to perform operations on variables and values. They help in
carrying out tasks such as arithmetic calculations, comparisons, logical decisions, and assigning
values.
$a = 10 + 5;
the + symbol is an operator that adds two values, and the = symbol is an operator that assigns
the result to a variable.
Arithmetic Operators
9
Web Technologies IV SEM BCA
+ Addition $a + $b
- Subtraction $a - $b
* Multiplication $a * $b
/ Division $a / $b
% Modulus (Remainder) $a % $b
Example
<?php
$a = 20;
$b = 10;
echo $a + $b;
echo "<br>";
echo $a - $b;
echo "<br>";
echo $a * $b;
echo "<br>";
echo $a / $b;
?>
Output:
30
10
200
2
Assignment Operators
Example
<?php
$x = 50;
echo $x;
?>
Output:
50
10
Web Technologies IV SEM BCA
+= $x += 5 $x = $x + 5
-= $x -= 5 $x = $x - 5
*= $x *= 5 $x = $x * 5
/= $x /= 5 $x = $x / 5
Example
<?php
$x = 10;
$x += 5;
echo $x;
?>
Output:
15
Comparison Operators
Comparison operators compare two values and return either TRUE or FALSE.
Operator Description
== Equal to
!= Not equal to
Example
<?php
$a = 10;
$b = 20;
11
Web Technologies IV SEM BCA
Output:
bool(true)
Logical Operators
Operator Description
` Logical OR
! Logical NOT
Example
<?php
$age = 20;
$citizen = true;
Output:
Eligible to Vote
echo $x;
?>
Output:
12
Web Technologies IV SEM BCA
$x--;
echo $x;
?>
Output:
String Operators
Example
<?php
$fname = "Data";
$lname = "Science";
Output:
Data Science
Ternary Operator
Syntax
condition ? value1 : value2;
Example
<?php
$age = 20;
Output:
Adult
<?php
$a = 15;
$b = 5;
13
Web Technologies IV SEM BCA
Output:
Addition: 20
Multiplication: 75
A is Greater
Operators are symbols used to perform various operations on variables and values in PHP.
Common types of operators include Arithmetic Operators, Assignment Operators,
Comparison Operators, Logical Operators, Increment/Decrement Operators, String
Operators, and Ternary Operators. They are essential for performing calculations, making
decisions, and manipulating data in PHP programs.
Strings and constants are important concepts in PHP programming. A string is used to store text
or a sequence of characters, while a constant is used to store a value that remains unchanged
throughout the execution of a program.
Both strings and constants are widely used in PHP applications for storing messages, names,
configuration values, and other important information.
Strings in PHP
A string is a sequence of characters enclosed within single quotes (' ') or double quotes (" ").
Strings are used to store text data such as names, addresses, messages, and descriptions.
Creating Strings
echo $name;
?>
14
Web Technologies IV SEM BCA
Output:
PHP Programming
echo $name;
?>
Output:
PHP Programming
String Concatenation
Concatenation means joining two or more strings together. In PHP, the dot (.) operator is used
for concatenation.
Example
<?php
$fname = "Data";
$lname = "Science";
Output:
Data Science
Example
<?php
$text = "PHP";
echo strlen($text);
?>
Output:
15
Web Technologies IV SEM BCA
String Functions
-> strtoupper()
<?php
echo strtoupper("php");
?>
Output:
PHP
-> strtolower()
<?php
echo strtolower("PHP");
?>
Output:
php
-> str_replace()
<?php
echo str_replace("PHP", "Python", "PHP Programming");
?>
Output:
Python Programming
Constants in PHP
A constant is a name or identifier whose value cannot be changed during the execution of a
program. Unlike variables, constants do not use the dollar sign ($).
Once a constant is defined, its value remains fixed throughout the script.
16
Web Technologies IV SEM BCA
Constants are commonly used to store values such as company names, tax rates, website URLs,
and mathematical values that should not be modified.
Creating Constants
Syntax
define("CONSTANT_NAME", value);
Example
<?php
define("COLLEGE", "Government Engineering College");
echo COLLEGE;
?>
Output:
Variable Constant
Example
<?php
$name = "PHP";
define("LANGUAGE", "PHP");
$name = "Python";
echo $name;
echo "<br>";
echo LANGUAGE;
?>
Output:
Python
17
Web Technologies IV SEM BCA
PHP
The variable value changes, but the constant value remains the same.
Example Program
<?php
$name = "Abhishek";
Output:
Strings are used to store and manipulate text data in PHP. They can be created using single or
double quotes and can be combined using concatenation operators. Constants are fixed values
that cannot be changed once defined. They are created using the define() function and are
commonly used for storing important values that should remain unchanged throughout a
program. Understanding strings and constants is essential for developing efficient PHP
applications.
An array is a special data structure in PHP that is used to store multiple values in a single
variable. Instead of creating separate variables for each value, an array allows related values to
be stored together and accessed using an index or key.
Arrays make programs more organized and reduce the number of variables required. They are
widely used for storing lists of names, marks, products, and other collections of data.
$student1 = "Ravi";
$student2 = "Kiran";
$student3 = "Anita";
18
Web Technologies IV SEM BCA
1. Indexed Arrays
2. Associative Arrays
3. Multidimensional Arrays
An indexed array stores elements with numeric indexes. By default, indexing starts from 0.
<?php
$colors = array("Red", "Green", "Blue");
echo $colors[0];
?>
Output:
Red
Here:
Index 0 → Red
Index 1 → Green
Index 2 → Blue
Example
<?php
$students = array("Ravi", "Kiran", "Anita");
echo $students[1];
?>
Output:
Kiran
19
Web Technologies IV SEM BCA
An associative array stores values using named keys instead of numeric indexes.
Accessing Elements
<?php
$student = array(
"name" => "Ravi",
"age" => 20
);
echo $student["name"];
?>
Output:
Ravi
In this example:
name → Ravi
age → 20
The values are accessed using keys rather than index numbers.
These arrays are useful for storing tabular data such as student records, employee information,
or marks lists.
20
Web Technologies IV SEM BCA
Accessing Elements
<?php
$students = array(
array("Ravi", 20),
array("Kiran", 21)
);
echo $students[0][0];
?>
Output:
Ravi
Explanation:
students[0][0] → Ravi
students[0][1] → 20
Example
<?php
$colors = array("Red", "Green", "Blue");
foreach($colors as $color)
{
echo $color . "<br>";
}
?>
Output:
Red
Green
Blue
Array Functions
21
Web Technologies IV SEM BCA
count()
<?php
$colors = array("Red", "Green", "Blue");
echo count($colors);
?>
Output:
sort()
<?php
$numbers = array(30, 10, 20);
sort($numbers);
print_r($numbers);
?>
Output:
Example Program
<?php
$fruits = array("Apple", "Mango", "Banana");
Output:
An array is a data structure used to store multiple values in a single variable. PHP supports
Indexed Arrays, Associative Arrays, and Multidimensional Arrays. Arrays help organize data
22
Web Technologies IV SEM BCA
efficiently and reduce the need for multiple variables. They are widely used in PHP applications
for storing and processing collections of related data such as names, marks, products, and
records.
Control structures are statements that determine the flow of execution of a PHP program.
Normally, PHP executes statements one after another in sequence. However, in many situations,
a program needs to make decisions, repeat certain tasks, or choose among multiple alternatives.
Control structures provide this capability.
Control structures help programmers control how and when different parts of a program are
executed. They are essential for creating dynamic and interactive applications.
1. Decision-Making Structures
2. Looping Structures
Decision-Making Structures
-> if Statement
Syntax
if(condition)
{
statements;
}
Example
<?php
$age = 20;
Output:
23
Web Technologies IV SEM BCA
Eligible to Vote
Syntax
if(condition)
{
statements;
}
else
{
statements;
}
Example
<?php
$marks = 35;
Output:
Fail
Example
<?php
$marks = 75;
24
Web Technologies IV SEM BCA
Output:
First Class
The switch statement is used when multiple conditions depend on the value of a single variable.
Syntax
switch(variable)
{
case value1:
statements;
break;
case value2:
statements;
break;
default:
statements;
}
Example
<?php
$day = 3;
switch($day)
{
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
case 3:
echo "Wednesday";
break;
25
Web Technologies IV SEM BCA
default:
echo "Invalid Day";
}
?>
Output:
Wednesday
Looping Structures
Looping structures are used to execute a block of code repeatedly until a specified condition
becomes false.
Syntax
while(condition)
{
statements;
}
Example
<?php
$i = 1;
while($i <= 5)
{
echo $i . "<br>";
$i++;
}
?>
Output:
1
2
3
4
5
The do...while loop executes the block at least once before checking the condition.
26
Web Technologies IV SEM BCA
Example
<?php
$i = 1;
do
{
echo $i . "<br>";
$i++;
}
while($i <= 5);
?>
Output:
1
2
3
4
5
The for loop is commonly used when the number of iterations is known in advance.
Syntax
for(initialization; condition; increment)
{
statements;
}
Example
<?php
for($i = 1; $i <= 5; $i++)
{
echo $i . "<br>";
}
?>
Output:
1
2
3
4
5
27
Web Technologies IV SEM BCA
Example
<?php
$colors = array("Red", "Green", "Blue");
foreach($colors as $color)
{
echo $color . "<br>";
}
?>
Output:
Red
Green
Blue
Example Program
<?php
$marks = 85;
echo "<br>";
Output:
Pass
PHP Programming
PHP Programming
PHP Programming
Control structures are used to control the execution flow of a PHP program. Decision-making
structures such as if, if-else, elseif, and switch help the program make choices based on
conditions. Looping structures such as while, do-while, for, and foreach allow repetitive
28
Web Technologies IV SEM BCA
execution of code. These structures are essential for developing dynamic and interactive PHP
applications.
A function is a block of code that performs a specific task. Functions help organize programs into
smaller, reusable units. Instead of writing the same code multiple times, a function can be
created once and called whenever needed.
Functions make programs easier to understand, maintain, and debug. PHP provides many built-
in functions, such as strlen(), count(), and date(). PHP also allows programmers to create their
own functions, known as user-defined functions.
Advantages of Functions
Functions offer several benefits in programming. They reduce code duplication, improve
readability, and make programs easier to maintain. If a change is required, it can be made in one
place instead of modifying the same code multiple times.
Functions also promote modular programming, where a large program is divided into smaller
manageable parts.
Creating a Function
Syntax
function function_name()
{
statements;
}
Example
<?php
function greet()
{
echo "Welcome to PHP Programming";
}
greet();
?>
Output:
In this example, the function greet() displays a welcome message when called.
29
Web Technologies IV SEM BCA
Parameters are values passed to a function when it is called. They allow the function to work
with different data.
Syntax
function function_name($parameter)
{
statements;
}
Example
<?php
function greet($name)
{
echo "Welcome " . $name;
}
greet("Ravi");
?>
Output:
Welcome Ravi
Example
<?php
function add($a, $b)
{
echo $a + $b;
}
add(10, 20);
?>
Output:
30
30
Web Technologies IV SEM BCA
Example
<?php
function square($num)
{
return $num * $num;
}
$result = square(5);
echo $result;
?>
Output:
25
The function calculates the square of a number and returns the result.
A function is a reusable block of code designed to perform a specific task. Functions help reduce
code duplication, improve program organization, and simplify maintenance. PHP supports both
built-in functions and user-defined functions. Functions can accept parameters, return values,
and make programs more modular and efficient. They are one of the most important concepts in
PHP programming and are widely used in web application development.
In traditional procedural programming, a program is divided into functions. In OOP, the program
is divided into objects that interact with each other to perform tasks.
For example, consider a student management system. Each student can be represented as an
object containing properties such as name, roll number, and course, along with methods such as
displayDetails() or calculateMarks(). This approach closely resembles real-world entities and
relationships.
31
Web Technologies IV SEM BCA
Class
A class is a blueprint or template used to create objects. It defines the properties and methods
that objects will have.
For example, a Student class may contain properties such as name and age, along with methods
to display student information.
Object
An object is an instance of a class. Once a class is created, multiple objects can be created from it.
For example:
Class → Student
Each object has its own data but shares the same structure defined by the class.
Advantages of OOP
Code reusability is one of the biggest benefits because classes can be reused in multiple
programs. OOP also improves code organization by grouping related data and functions together.
Programs become easier to maintain because changes can be made within a class without
affecting the entire application. OOP also supports modularity, making large projects easier to
develop and manage.
Another advantage is that OOP closely models real-world entities, making programs easier to
understand.
Web Applications
E-commerce Websites
Content Management Systems (CMS)
Banking Applications
Enterprise Software
Framework-Based Applications
32
Web Technologies IV SEM BCA
Properties and methods are the fundamental building blocks of Object-Oriented Programming
(OOP). A class is made up of properties and methods that describe the characteristics and
behavior of an object.
In simple terms, properties represent the data of an object, while methods represent the
actions performed by the object.
Consider a real-world example of a student. A student has characteristics such as name, age, and
course. These characteristics are represented as properties. A student can also perform actions
such as displaying details or calculating marks. These actions are represented as methods.
Properties
Properties are variables declared inside a class. They store the data associated with an object.
Syntax
class ClassName
{
public $propertyName;
}
Example
<?php
class Student
{
public $name = "Ravi";
public $age = 20;
}
?>
In this example:
$name is a property.
$age is a property.
Accessing Properties
<?php
class Student
{
public $name = "Ravi";
}
33
Web Technologies IV SEM BCA
echo $obj->name;
?>
Output:
Ravi
Methods
Methods are functions defined inside a class. They describe the behavior or actions that an object
can perform.
Syntax
class ClassName
{
public function methodName()
{
statements;
}
}
Example
<?php
class Student
{
public function display()
{
echo "Welcome to PHP";
}
}
$obj->display();
?>
Output:
Welcome to PHP
34
Web Technologies IV SEM BCA
Example
<?php
class Student
{
public $name = "Ravi";
$obj->display();
?>
Output:
Ravi
Here:
$name is a property.
display() is a method.
$this->name refers to the property of the current object.
The keyword $this is used to access properties and methods belonging to the current object.
Example Program
<?php
class Employee
{
public $name = "Anita";
public $salary = 50000;
35
Web Technologies IV SEM BCA
$emp->displayDetails();
?>
Output:
Name: Anita
Salary: 50000
Properties and methods are the core components of a class in Object-Oriented Programming.
Properties are variables that store the characteristics of an object, while methods are functions
that define the actions performed by the object. Together, they help model real-world entities in
software and make PHP programs more organized, reusable, and easier to maintain.
In Object-Oriented Programming (OOP), constructors and destructors are special methods that
are automatically called at specific stages of an object's life cycle. A constructor is executed
when an object is created, while a destructor is executed when an object is destroyed or when
the script ends.
These special methods help initialize objects and perform cleanup operations automatically
without requiring explicit method calls.
Constructor
Syntax
class ClassName
{
public function __construct()
{
statements;
}
}
Example
<?php
class Student
{
public function __construct()
{
echo "Object Created";
}
}
36
Web Technologies IV SEM BCA
Output:
Object Created
In this example, the constructor is automatically executed when the object is created.
<?php
class Student
{
public $name;
$obj->display();
?>
Output:
Ravi
Here, the constructor receives the value "Ravi" and stores it in the property $name.
Advantages of Constructor
37
Web Technologies IV SEM BCA
Destructor
A destructor is a special method that is automatically called when an object is destroyed or when
the script finishes execution.
Destructors are commonly used to release resources, close files, or perform cleanup operations.
Syntax
class ClassName
{
public function __destruct()
{
statements;
}
}
Example
<?php
class Student
{
public function __destruct()
{
echo "Object Destroyed";
}
}
Output:
Object Destroyed
The message appears automatically when the script ends and the object is destroyed.
38
Web Technologies IV SEM BCA
Output:
Object Created
Object Destroyed
In this example:
Access modifiers are keywords used in Object-Oriented Programming (OOP) to control the
visibility and accessibility of properties and methods within a class. They determine where a
property or method can be accessed from.
Access modifiers help implement data hiding and encapsulation, which are important
principles of OOP. By controlling access to data, programmers can protect important information
from being modified accidentally.
1. Public
2. Private
3. Protected
The public access modifier allows properties and methods to be accessed from anywhere in the
program.
Example
<?php
class Student
{
39
Web Technologies IV SEM BCA
echo $obj->name;
?>
Output:
Ravi
The private access modifier allows properties and methods to be accessed only within the same
class.
Private members cannot be accessed directly from outside the class or by child classes.
Example
<?php
class Student
{
private $name = "Ravi";
$obj->display();
?>
Output:
Ravi
In this example, the private property $name is accessed through a public method.
echo $obj->name;
40
Web Technologies IV SEM BCA
Private members provide maximum security and prevent direct access to sensitive data.
However, protected members cannot be accessed directly from outside the class.
Example
<?php
class Student
{
protected $name = "Ravi";
}
$obj->display();
?>
Output:
Ravi
Here, the child class College can access the protected property $name.
echo $obj->name;
because protected members cannot be accessed directly from outside the class.
41
Web Technologies IV SEM BCA
<?php
class Demo
{
public $a = "Public";
protected $b = "Protected";
private $c = "Private";
$obj->display();
?>
Output:
Public
Protected
Private
Inside the class, all members can be accessed regardless of their access modifier.
Access modifiers are used to control the visibility of properties and methods in a PHP class. The
public modifier allows access from anywhere, protected allows access within the class and its
child classes, and private restricts access to the same class only. Access modifiers improve
security, support encapsulation, and help create well-structured Object-Oriented PHP
applications.
The class whose properties and methods are inherited is called the Parent Class (or Base Class),
and the class that inherits them is called the Child Class (or Derived Class).
42
Web Technologies IV SEM BCA
Suppose a program contains multiple classes with similar properties and methods. Instead of
rewriting the same code in every class, a common parent class can be created, and other classes
can inherit its features.
This makes the program more organized, reusable, and easier to maintain.
Syntax of Inheritance
class ParentClass
{
// Properties and methods
}
Example
<?php
class Animal
{
public function eat()
{
echo "Animal is eating";
}
}
$dog->eat();
?>
Output:
Animal is eating
Here, the Dog class inherits the eat() method from the Animal class.
1. Single Inheritance
43
Web Technologies IV SEM BCA
In Single Inheritance, one child class inherits from one parent class.
Example
<?php
class Vehicle
{
public function start()
{
echo "Vehicle Started";
}
}
$car->start();
?>
Output:
Vehicle Started
In this case, the Car class inherits from the Vehicle class.
2. Multilevel Inheritance
In Multilevel Inheritance, a class inherits from another child class, creating multiple levels.
Example
<?php
class Animal
{
public function eat()
{
echo "Eating";
}
}
44
Web Technologies IV SEM BCA
$obj->eat();
?>
Output:
Eating
Here:
Animal
↓
Dog
↓
Puppy
3. Hierarchical Inheritance
In Hierarchical Inheritance, multiple child classes inherit from the same parent class.
Example
<?php
class Animal
{
public function eat()
{
echo "Eating";
}
}
$dog->eat();
?>
Output:
45
Web Technologies IV SEM BCA
Eating
Structure:
Animal
/ \
Dog Cat
Class C extends A, B
However, PHP achieves multiple inheritance using interfaces, which will be studied later.
Method Overriding
Method Overriding occurs when a child class provides its own implementation of a method that
already exists in the parent class.
The child class method replaces the parent class method when called through an object of the
child class.
<?php
class Animal
{
public function sound()
{
echo "Animal makes sound";
}
}
46
Web Technologies IV SEM BCA
}
}
$dog->sound();
?>
Output:
Dog barks
Although the parent class contains a sound() method, the child class provides its own version.
Therefore, the child class method is executed.
Method overriding allows child classes to modify inherited behavior without changing the parent
class. It increases flexibility and supports polymorphism in Object-Oriented Programming.
Inheritance is an OOP feature that allows one class to acquire the properties and methods of
another class. The main types of inheritance in PHP are Single Inheritance, Multilevel
Inheritance, and Hierarchical Inheritance. Method Overriding allows a child class to provide
its own implementation of a parent class method. Together, inheritance and overriding improve
code reusability, flexibility, and maintainability in PHP applications.
Abstract Class
An abstract class is a class that cannot be instantiated directly. It is used as a blueprint for other
classes. An abstract class may contain both abstract methods (without a body) and normal
methods (with a body).
Example
<?php
abstract class Animal
{
abstract public function sound();
}
47
Web Technologies IV SEM BCA
Output:
Dog barks
Key Points
Interface
An interface is a completely abstract structure that contains only method declarations. It defines
what a class must do, but not how it should do it.
Example
<?php
interface Animal
{
public function sound();
}
Output:
Dog barks
Key Points
48
Web Technologies IV SEM BCA
Can contain abstract and normal methods Contains only method declarations
An Abstract Class provides a partial implementation and acts as a blueprint for child classes. An
Interface provides only method declarations and forces classes to implement them. Abstract
classes define what a class is, while interfaces define what a class can do.
Superglobals are predefined variables in PHP that are available throughout the script. They can
be accessed from any function, class, or file without using the global keyword.
PHP provides several superglobal arrays to handle user input, server information, session data,
and more.
Common Superglobals
$_GET
$name = $_GET['name'];
$_POST
$name = $_POST['name'];
49
Web Technologies IV SEM BCA
$_REQUEST
$name = $_REQUEST['name'];
$_SERVER
echo $_SERVER['PHP_SELF'];
$_SESSION
$_SESSION['username'] = "Ravi";
$_COOKIE
echo $_COOKIE['user'];
$_FILES
$_FILES['file'];
$_GLOBALS
$GLOBALS['x'];
Superglobals are predefined PHP variables that can be accessed anywhere in a program.
Common superglobals include $_GET, $_POST, $_REQUEST, $_SERVER, $_SESSION, $_COOKIE,
$_FILES, and $GLOBALS. They are widely used for handling user input, sessions, cookies, file
uploads, and server information.
Forms are one of the most important parts of a web application. They allow users to enter data
such as names, email addresses, passwords, feedback, and other information. PHP can collect
this data, process it on the server, and perform validation before using or storing it.
50
Web Technologies IV SEM BCA
Form Handling refers to the process of receiving and processing data submitted through an
HTML form. Form Validation refers to checking whether the user has entered valid and
acceptable data before processing it.
A form sends data to a PHP script using either the GET or POST method.
When the user clicks the Submit button, the data is sent to [Link].
Welcome Ravi
Example URL:
[Link]?username=Ravi
PHP code:
<?php
echo $_GET['username'];
?>
Output:
Ravi
51
Web Technologies IV SEM BCA
The POST method sends data in the request body and does not display it in the URL.
<?php
echo $_POST['username'];
?>
The POST method is preferred for passwords, personal details, and sensitive information.
Form Validation
Validation is the process of checking whether the entered data is correct and complete.
Empty values
Invalid email addresses
Incorrect phone numbers
Special characters
Complete Example
HTML Form
<form method="post" action="[Link]">
Name:
<input type="text" name="name"><br><br>
Email:
<input type="text" name="email"><br><br>
PHP Validation
<?php
$name = $_POST['name'];
$email = $_POST['email'];
if(empty($name))
{
52
Web Technologies IV SEM BCA
?>
Output:
Form validation ensures that only valid data is submitted to the server. It improves data
accuracy, prevents errors, enhances security, and provides a better user experience.
PHP Form Handling is the process of collecting and processing data submitted through HTML
forms using methods such as GET and POST. Form Validation checks whether the entered data is
correct before processing it. Common validations include checking required fields, email
formats, and numeric values. Proper form handling and validation are essential for creating
secure and reliable web applications.
File uploading allows users to upload files such as images, documents, videos, and PDFs from a
web page to the server. PHP provides the $_FILES superglobal to handle uploaded files.
To upload files, the HTML form must use the multipart/form-data encoding type.
HTML Form
<form action="[Link]" method="post" enctype="multipart/form-data">
Select File:
<input type="file" name="myfile">
53
Web Technologies IV SEM BCA
PHP Script
<?php
move_uploaded_file(
$_FILES["myfile"]["tmp_name"],
"uploads/" . $_FILES["myfile"]["name"]
);
Output:
The uploaded file is moved from a temporary location to the specified folder.
File uploading enables users to transfer files from their computers to the server using the
$_FILES superglobal.
Cookies in PHP
A cookie is a small file stored on the user's computer by the web browser. Cookies are used to
remember user preferences, login information, and other data across multiple visits.
Syntax
setcookie(name, value, expiry_time);
Example
<?php
setcookie("username", "Ravi", time()+3600);
Output:
Cookie Created
Reading a Cookie
<?php
echo $_COOKIE["username"];
?>
Output:
54
Web Technologies IV SEM BCA
Ravi
Cookies store small amounts of data on the user's computer and help websites remember
information between visits.
Sessions in PHP
A session is used to store user information on the server. Unlike cookies, session data is stored
on the server, making it more secure.
Sessions are commonly used to maintain login information and user-specific data across
multiple pages.
Starting a Session
<?php
session_start();
$_SESSION["username"] = "Ravi";
Output:
Session Created
echo $_SESSION["username"];
?>
Output:
Ravi
Destroying a Session
<?php
session_start();
session_destroy();
?>
Sessions store user information on the server and are widely used for authentication, login
systems, and maintaining user state across web pages.
55
Web Technologies IV SEM BCA
Errors are problems that occur during the execution of a program. Error handling helps identify,
manage, and respond to these problems gracefully.
Parse Errors
Fatal Errors
Warning Errors
Notice Errors
Example of an Error
<?php
echo $name;
?>
Displaying Errors
<?php
error_reporting(E_ALL);
?>
Exception Handling
Example
<?php
try
{
throw new Exception("Something went wrong");
}
catch(Exception $e)
{
echo $e->getMessage();
}
?>
Output:
56
Web Technologies IV SEM BCA
The try block contains code that may generate an exception. The catch block handles the
exception and displays the error message.
Error handling helps detect problems, prevents program crashes, improves debugging, and
provides a better user experience by displaying meaningful messages instead of unexpected
failures.
Error handling is the process of detecting and managing errors during program execution. PHP
provides error-reporting functions and exception handling using try, catch, and throw. Proper
error handling makes applications more reliable, secure, and easier to maintain.
PHP can connect to a MySQL database using the mysqli_connect() function. A database
connection allows PHP programs to store, retrieve, update, and delete data from the database.
Syntax
mysqli_connect(hostname, username, password, database_name);
Example
<?php
$conn = mysqli_connect(
"localhost",
"root",
"",
"studentdb"
);
if($conn)
{
echo "Connection Successful";
}
else
{
echo "Connection Failed";
}
?>
Output:
Connection Successful
57
Web Technologies IV SEM BCA
Explanation
Closing Connection
<?php
mysqli_close($conn);
?>
PHP connects to a MySQL database using the mysqli_connect() function. A successful connection
enables PHP applications to interact with the database and manage data efficiently.
CRUD stands for Create, Read, Update, and Delete. These are the four basic operations
performed on database records. PHP uses SQL queries along with a database connection to
perform CRUD operations.
id name course
1 Ravi BCA
<?php
$conn = mysqli_connect("localhost","root","","studentdb");
mysqli_query($conn, $sql);
?>
Output:
58
Web Technologies IV SEM BCA
Record Inserted
<?php
$conn = mysqli_connect("localhost","root","","studentdb");
$result = mysqli_query(
$conn,
"SELECT * FROM students"
);
while($row = mysqli_fetch_assoc($result))
{
echo $row["name"] . " - " . $row["course"];
echo "<br>";
}
?>
Output:
Ravi - BCA
<?php
$conn = mysqli_connect("localhost","root","","studentdb");
mysqli_query($conn, $sql);
?>
Output:
Record Updated
59
Web Technologies IV SEM BCA
<?php
$conn = mysqli_connect("localhost","root","","studentdb");
mysqli_query($conn, $sql);
?>
Output:
Record Deleted
CRUD operations are the basic database operations used in PHP applications. INSERT adds new
records, SELECT retrieves data, UPDATE modifies existing records, and DELETE removes
records. Together, these operations form the foundation of database-driven web applications.
Prepared statements are used to execute SQL queries securely. They help prevent SQL Injection
attacks by separating SQL code from user input.
A prepared statement first creates the SQL query with placeholders (?), and then actual values
are supplied using bound parameters.
Example
<?php
60
Web Technologies IV SEM BCA
$conn = mysqli_connect("localhost","root","","studentdb");
$stmt = mysqli_prepare(
$conn,
"INSERT INTO students(name, course)
VALUES(?, ?)"
);
mysqli_stmt_bind_param(
$stmt,
"ss",
$name,
$course
);
$name = "Ravi";
$course = "BCA";
mysqli_stmt_execute($stmt);
?>
Output:
Record Inserted
Here:
? are placeholders.
bind_param() binds values to placeholders.
"ss" means both parameters are strings.
Prepared statements improve security and performance by separating SQL queries from user
data.
Limiting Data
Sometimes only a specific number of records are required. The SQL LIMIT clause is used for this
purpose.
Example
<?php
$result = mysqli_query(
$conn,
61
Web Technologies IV SEM BCA
?>
This skips the first 2 records and retrieves the next 5 records.
The LIMIT clause is used to restrict the number of records returned by a query and is commonly
used in pagination.
When a new record is inserted into a table with an AUTO_INCREMENT primary key, MySQL
automatically generates an ID.
PHP provides the mysqli_insert_id() function to retrieve the last inserted ID.
Example
<?php
$conn = mysqli_connect("localhost","root","","studentdb");
mysqli_query($conn, $sql);
$last_id = mysqli_insert_id($conn);
?>
Output:
The mysqli_insert_id() function returns the ID generated by the most recent INSERT operation. It
is useful when working with tables that use AUTO_INCREMENT primary keys and when related
records need to be inserted into other tables.
62