0% found this document useful (0 votes)
3 views62 pages

WT Chapter 5

Uploaded by

lakshmi2yadav28
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views62 pages

WT Chapter 5

Uploaded by

lakshmi2yadav28
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Web Technologies IV SEM BCA

Chapter-05
Server-side Scripting with PHP

5.1 Introduction to 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.

5.2 Features of PHP

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.

3. Easy to Learn and Use

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.

6. Supports Object-Oriented Programming

PHP supports Object-Oriented Programming (OOP), allowing developers to create reusable and
well-structured code using classes and objects.

7. Strong Community Support

PHP has a large developer community worldwide. As a result, extensive documentation,


tutorials, libraries, and frameworks are available to help developers solve problems quickly.

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.

5.3 Setting Up XAMPP Server and Running a PHP Script

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.

Step 1: Download XAMPP

Visit the official XAMPP website and download the version suitable for your operating system.

Apache Friends (XAMPP)

Choose the appropriate version for Windows, Linux, or macOS.

Step 2: Install XAMPP

After downloading the installer:

1. Double-click the XAMPP installation file.


2. Click Next through the installation wizard.
3. Select the required components (Apache, MySQL, PHP).
4. Choose the installation location (usually C:\xampp).
5. Complete the installation process.

Once installed, the XAMPP Control Panel will be available.

Step 3: Start Apache Server

Open the XAMPP Control Panel.

2
Web Technologies IV SEM BCA

You will see several services:

Apache
MySQL
FileZilla
Tomcat
Mercury

Click the Start button next to Apache.

If Apache starts successfully, its status will turn green.

Apache [Running]

For PHP programs, only Apache is required.

Step 4: Verify XAMPP Installation

Open a web browser and type:

[Link]

If XAMPP is installed correctly, the XAMPP welcome page will appear.

Congratulations. Your computer is now pretending to be a web server. Humans do enjoy making
one computer act like another computer.

Step 5: Locate the htdocs Folder

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.

Step 6: Create a PHP File

Open Notepad or any code editor.

Create a file named:

[Link]

Write the following PHP code:

<?php
echo "Hello, World!";
?>

3
Web Technologies IV SEM BCA

Save the file inside:

C:\xampp\htdocs

Step 7: Run the PHP Script

Open a web browser and type:

[Link]

Output:

Hello, World!

The PHP code is executed by the server, and the browser displays only the output.

Example 2: Displaying Student Information

Create a file named:

[Link]

Write:

<?php
$name = "Ramesh";
$course = "Data Science";

echo "Name: " . $name . "<br>";


echo "Course: " . $course;
?>

Save it in:

C:\xampp\htdocs

Run:

[Link]

Output:

Name: Ramesh
Course: Data Science

Step 8: Stopping the Server

After completing your work:

1. Open XAMPP Control Panel.


2. Click Stop next to Apache.

4
Web Technologies IV SEM BCA

Apache [Stopped]

Stopping unused services saves system resources.

Folder Structure Example

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.

5.4 Variables and Data Types in PHP

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.

Rules for Naming Variables

 A variable name must start with a dollar sign ($).


 The first character after $ must be a letter or underscore (_).
 Variable names cannot start with a number.
 Variable names are case-sensitive.
 Special characters such as @, #, %, and spaces are not allowed.

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

Values can be assigned to variables using the assignment operator (=).

<?php
$city = "Mysuru";
$population = 1000000;
?>

Here, the value "Mysuru" is assigned to $city, and 1000000 is assigned to $population.

Data Types in PHP

A data type specifies the type of value stored in a variable. PHP supports several built-in data
types.

-> Integer

An integer is a whole number without decimal points.

Example:

<?php
$marks = 85;
echo $marks;
?>

Output:

85

-> Float (Double)

A float is a number containing decimal points.

6
Web Technologies IV SEM BCA

Example:

<?php
$price = 99.99;
echo $price;
?>

Output:

99.99

-> String

A string is a sequence of characters enclosed within single quotes or double quotes.

Example:

<?php
$name = "PHP Programming";
echo $name;
?>

Output:

PHP Programming

-> Boolean

A Boolean data type can store only two values:

TRUE
FALSE

Example:

<?php
$isStudent = true;
?>

Boolean values are commonly used in decision-making statements.

-> Array

An array is used to store multiple values in a single variable.

Example:

<?php
$colors = array("Red", "Green", "Blue");

echo $colors[0];

7
Web Technologies IV SEM BCA

?>

Output:

Red

-> NULL

The NULL data type represents a variable with no value.

Example:

<?php
$subject = NULL;
?>

The variable exists but contains no data.

-> Object

Objects are instances of classes used in Object-Oriented Programming (OOP).

Example:

<?php
class Student {
public $name = "Ravi";
}

$obj = new Student();


echo $obj->name;
?>

Output:

Ravi

Checking Data Type

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

Example Using Different Data Types


<?php
$name = "Anita";
$age = 21;
$percentage = 89.5;
$isPassed = true;

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.

5.5 Operators in PHP

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.

For example, in the expression:

$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.

PHP provides several types of operators for different purposes.

Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations.

9
Web Technologies IV SEM BCA

Operator Description Example

+ 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

Assignment operators are used to assign values to variables.

The most common assignment operator is =.

Example
<?php
$x = 50;
echo $x;
?>

Output:

50

PHP also provides shorthand assignment operators.

10
Web Technologies IV SEM BCA

Operator Example Meaning

+= $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

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

Example
<?php
$a = 10;
$b = 20;

var_dump($a < $b);


?>

11
Web Technologies IV SEM BCA

Output:

bool(true)

Logical Operators

Logical operators are used to combine multiple conditions.

Operator Description

&& Logical AND

` Logical OR

! Logical NOT

Example
<?php
$age = 20;
$citizen = true;

if($age >= 18 && $citizen == true)


{
echo "Eligible to Vote";
}
?>

Output:

Eligible to Vote

Increment and Decrement Operators

These operators increase or decrease a variable's value by one.

Increment Operator (++)


<?php
$x = 5;
$x++;

echo $x;
?>

Output:

Decrement Operator (--)


<?php
$x = 5;

12
Web Technologies IV SEM BCA

$x--;

echo $x;
?>

Output:

String Operators

String operators are used to join strings.

The dot (.) operator is used for concatenation.

Example
<?php
$fname = "Data";
$lname = "Science";

echo $fname . " " . $lname;


?>

Output:

Data Science

Ternary Operator

The ternary operator is a shorthand form of the if-else statement.

Syntax
condition ? value1 : value2;

Example
<?php
$age = 20;

echo ($age >= 18) ? "Adult" : "Minor";


?>

Output:

Adult

Example Using Multiple Operators

<?php
$a = 15;
$b = 5;

13
Web Technologies IV SEM BCA

echo "Addition: " . ($a + $b);


echo "<br>";

echo "Multiplication: " . ($a * $b);


echo "<br>";

echo ($a > $b) ? "A is Greater" : "B is Greater";


?>

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.

5.6 Strings and Constants in PHP

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

A string can be created using either single quotes or double quotes.

Example Using Double Quotes


<?php
$name = "PHP Programming";

echo $name;
?>

14
Web Technologies IV SEM BCA

Output:

PHP Programming

Example Using Single Quotes


<?php
$name = 'PHP Programming';

echo $name;
?>

Output:

PHP Programming

Both methods produce the same output.

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";

echo $fname . " " . $lname;


?>

Output:

Data Science

The dot operator combines the two strings into one.

-> String Length

The strlen() function is used to find the length of a string.

Example
<?php
$text = "PHP";

echo strlen($text);
?>

Output:

15
Web Technologies IV SEM BCA

The output is 3 because the string contains three characters.

String Functions

PHP provides several built-in functions for working with strings.

-> strtoupper()

Converts a string to uppercase.

<?php
echo strtoupper("php");
?>

Output:

PHP

-> strtolower()

Converts a string to lowercase.

<?php
echo strtolower("PHP");
?>

Output:

php

-> str_replace()

Replaces part of a string with another string.

<?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

The define() function is used to create constants.

Syntax
define("CONSTANT_NAME", value);

Example
<?php
define("COLLEGE", "Government Engineering College");

echo COLLEGE;
?>

Output:

Government Engineering College

The value of COLLEGE cannot be changed later in the program.

Difference Between Variables and Constants

Variable Constant

Starts with $ symbol Does not use $ symbol

Value can be changed Value cannot be changed

Created using assignment operator Created using define()

Example: $name = "PHP" Example: define("NAME","PHP")

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";

define("COURSE", "Data Science");

echo "Student Name: " . $name;


echo "<br>";
echo "Course: " . COURSE;
?>

Output:

Student Name: Abhishek


Course: Data Science

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.

5.7 Arrays in PHP

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.

For example, instead of writing:

$student1 = "Ravi";
$student2 = "Kiran";
$student3 = "Anita";

we can use an array:

$students = array("Ravi", "Kiran", "Anita");

This stores multiple values in a single variable.

Types of Arrays in PHP

18
Web Technologies IV SEM BCA

PHP supports three main types of arrays:

1. Indexed Arrays
2. Associative Arrays
3. Multidimensional Arrays

-> Indexed Arrays

An indexed array stores elements with numeric indexes. By default, indexing starts from 0.

Creating an Indexed Array


<?php
$colors = array("Red", "Green", "Blue");
?>

Accessing Array Elements

Array elements are accessed using their index number.

<?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

-> Associative Arrays

19
Web Technologies IV SEM BCA

An associative array stores values using named keys instead of numeric indexes.

This makes the data easier to understand and access.

Creating an Associative Array


<?php
$student = array(
"name" => "Ravi",
"age" => 20,
"course" => "BCA"
);
?>

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.

-> Multidimensional Arrays

A multidimensional array contains one or more arrays inside another array.

These arrays are useful for storing tabular data such as student records, employee information,
or marks lists.

Creating a Multidimensional Array


<?php
$students = array(
array("Ravi", 20),
array("Kiran", 21),
array("Anita", 22)
);
?>

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] → First row

students[0][0] → Ravi

students[0][1] → 20

Displaying Array Elements Using Loop

Arrays are often used with loops to display all elements.

Example
<?php
$colors = array("Red", "Green", "Blue");

foreach($colors as $color)
{
echo $color . "<br>";
}
?>

Output:

Red
Green
Blue

The foreach loop automatically visits each element of the array.

Array Functions

PHP provides several built-in functions for working with arrays.

21
Web Technologies IV SEM BCA

count()

Returns the number of elements in an array.

<?php
$colors = array("Red", "Green", "Blue");

echo count($colors);
?>

Output:

sort()

Sorts an array in ascending order.

<?php
$numbers = array(30, 10, 20);

sort($numbers);

print_r($numbers);
?>

Output:

Array ( [0] => 10 [1] => 20 [2] => 30 )

Example Program

<?php
$fruits = array("Apple", "Mango", "Banana");

echo "First Fruit: " . $fruits[0];


echo "<br>";

echo "Total Fruits: " . count($fruits);


?>

Output:

First Fruit: Apple


Total Fruits: 3

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.

5.8 Control Structures in PHP

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.

PHP mainly provides two categories of control structures:

1. Decision-Making Structures
2. Looping Structures

Decision-Making Structures

Decision-making structures allow a program to execute different blocks of code based on


specified conditions.

-> if Statement

The if statement executes a block of code only when a condition is true.

Syntax
if(condition)
{
statements;
}

Example
<?php
$age = 20;

if($age >= 18)


{
echo "Eligible to Vote";
}
?>

Output:

23
Web Technologies IV SEM BCA

Eligible to Vote

In this example, the message is displayed because the condition is true.

-> if...else Statement

The if...else statement provides two possible execution paths.

Syntax
if(condition)
{
statements;
}
else
{
statements;
}

Example
<?php
$marks = 35;

if($marks >= 40)


{
echo "Pass";
}
else
{
echo "Fail";
}
?>

Output:

Fail

-> if...elseif...else Statement

This structure is used when multiple conditions need to be checked.

Example
<?php
$marks = 75;

if($marks >= 80)


{
echo "Distinction";
}

24
Web Technologies IV SEM BCA

elseif($marks >= 60)


{
echo "First Class";
}
else
{
echo "Pass";
}
?>

Output:

First Class

-> switch Statement

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.

-> while Loop

The while loop executes as long as the condition remains true.

Syntax
while(condition)
{
statements;
}

Example
<?php
$i = 1;

while($i <= 5)
{
echo $i . "<br>";
$i++;
}
?>

Output:

1
2
3
4
5

-> do...while Loop

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

-> for Loop

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

-> foreach Loop

The foreach loop is used to access elements of an array.

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;

if($marks >= 40)


{
echo "Pass";
}
else
{
echo "Fail";
}

echo "<br>";

for($i = 1; $i <= 3; $i++)


{
echo "PHP Programming<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.

5.9 Functions in PHP

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

A function is created using the function keyword.

Syntax
function function_name()
{
statements;
}

Example
<?php
function greet()
{
echo "Welcome to PHP Programming";
}

greet();
?>

Output:

Welcome to PHP Programming

In this example, the function greet() displays a welcome message when called.

29
Web Technologies IV SEM BCA

-> Function with Parameters

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

The value "Ravi" is passed to the function as a parameter.

-> Function with Multiple Parameters

A function can accept more than one parameter.

Example
<?php
function add($a, $b)
{
echo $a + $b;
}

add(10, 20);
?>

Output:

30

The function receives two numbers and displays their sum.

30
Web Technologies IV SEM BCA

-> Returning Values from a Function

Functions can return values using the return statement.

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.

5.10 Introduction to Object-Oriented Programming (OOP) in PHP

Object-Oriented Programming (OOP) is a programming paradigm that organizes programs


around objects rather than functions and logic alone. An object represents a real-world entity
and contains both data and the operations that can be performed on that data.

PHP supports Object-Oriented Programming, allowing developers to create modular, reusable,


and well-structured applications. OOP is widely used in modern PHP development because it
makes programs easier to maintain, extend, and manage.

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.

Basic Concepts of OOP

31
Web Technologies IV SEM BCA

Object-Oriented Programming is based on several important concepts:

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

Objects → Ravi, Anita, Kiran

Each object has its own data but shares the same structure defined by the class.

Advantages of OOP

Object-Oriented Programming offers several advantages over procedural programming.

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.

Applications of OOP in PHP

OOP is widely used in developing:

 Web Applications
 E-commerce Websites
 Content Management Systems (CMS)
 Banking Applications
 Enterprise Software
 Framework-Based Applications

32
Web Technologies IV SEM BCA

5.11 Properties and Methods in PHP

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.

Properties describe the characteristics or attributes of 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.

These properties store information about a student.

Accessing Properties

Properties are accessed using the object operator (->).

<?php
class Student
{
public $name = "Ravi";
}

33
Web Technologies IV SEM BCA

$obj = new Student();

echo $obj->name;
?>

Output:

Ravi

The object $obj accesses the property $name.

Methods

Methods are functions defined inside a class. They describe the behavior or actions that an object
can perform.

Methods often use properties to perform operations.

Syntax
class ClassName
{
public function methodName()
{
statements;
}
}

Example
<?php
class Student
{
public function display()
{
echo "Welcome to PHP";
}
}

$obj = new Student();

$obj->display();
?>

Output:

Welcome to PHP

In this example, display() is a method that displays a message.

34
Web Technologies IV SEM BCA

Using Properties and Methods Together

Methods often work with properties of the same object.

Example
<?php
class Student
{
public $name = "Ravi";

public function display()


{
echo $this->name;
}
}

$obj = new Student();

$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;

public function displayDetails()


{
echo "Name: " . $this->name;
echo "<br>";
echo "Salary: " . $this->salary;
}
}

35
Web Technologies IV SEM BCA

$emp = new Employee();

$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.

5.12 Constructors and Destructors in PHP

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

A constructor is a special method that is automatically called whenever an object of a class is


created. It is mainly used to initialize properties of the object.

In PHP, a constructor is defined using the __construct() method.

Syntax
class ClassName
{
public function __construct()
{
statements;
}
}

Example
<?php
class Student
{
public function __construct()
{
echo "Object Created";
}
}

36
Web Technologies IV SEM BCA

$obj = new Student();


?>

Output:

Object Created

In this example, the constructor is automatically executed when the object is created.

Constructor with Parameters

A constructor can also accept parameters to initialize object properties.

<?php
class Student
{
public $name;

public function __construct($n)


{
$this->name = $n;
}

public function display()


{
echo $this->name;
}
}

$obj = new Student("Ravi");

$obj->display();
?>

Output:

Ravi

Here, the constructor receives the value "Ravi" and stores it in the property $name.

Advantages of Constructor

 Automatically initializes object data.


 Reduces repetitive code.
 Ensures objects are created in a valid state.
 Improves program organization.

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.

In PHP, a destructor is defined using the __destruct() method.

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";
}
}

$obj = new Student();


?>

Output:

Object Destroyed

The message appears automatically when the script ends and the object is destroyed.

Example with Constructor and Destructor


<?php
class Student
{
public function __construct()
{
echo "Object Created";
echo "<br>";
}

public function __destruct()


{
echo "Object Destroyed";
}

38
Web Technologies IV SEM BCA

$obj = new Student();


?>

Output:

Object Created
Object Destroyed

In this example:

1. The constructor runs when the object is created.


2. The destructor runs when the script ends.

5.13 Access Modifiers in PHP

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.

PHP provides three access modifiers:

1. Public
2. Private
3. Protected

-> Public Access Modifier

The public access modifier allows properties and methods to be accessed from anywhere in the
program.

A public member can be accessed:

 Inside the class


 Outside the class
 By child classes

Example
<?php
class Student
{

39
Web Technologies IV SEM BCA

public $name = "Ravi";


}

$obj = new Student();

echo $obj->name;
?>

Output:

Ravi

Since $name is public, it can be accessed directly through the object.

-> Private Access Modifier

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";

public function display()


{
echo $this->name;
}
}

$obj = new Student();

$obj->display();
?>

Output:

Ravi

In this example, the private property $name is accessed through a public method.

The following code would produce an error:

echo $obj->name;

because $name is private.

40
Web Technologies IV SEM BCA

Why Use Private?

Private members provide maximum security and prevent direct access to sensitive data.

-> Protected Access Modifier

The protected access modifier allows properties and methods to be accessed:

 Inside the same class


 By child classes (inherited classes)

However, protected members cannot be accessed directly from outside the class.

Example
<?php
class Student
{
protected $name = "Ravi";
}

class College extends Student


{
public function display()
{
echo $this->name;
}
}

$obj = new College();

$obj->display();
?>

Output:

Ravi

Here, the child class College can access the protected property $name.

The following would produce an error:

echo $obj->name;

because protected members cannot be accessed directly from outside the class.

Example Using All Access Modifiers

41
Web Technologies IV SEM BCA

<?php
class Demo
{
public $a = "Public";

protected $b = "Protected";

private $c = "Private";

public function display()


{
echo $this->a;
echo "<br>";
echo $this->b;
echo "<br>";
echo $this->c;
}
}

$obj = new Demo();

$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.

5.14 Inheritance and Method Overriding in PHP

Inheritance is one of the most important features of Object-Oriented Programming (OOP). It


allows a class to acquire the properties and methods of another class. Inheritance promotes code
reusability and helps reduce duplication of code.

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).

In PHP, inheritance is implemented using the extends keyword.

Need for Inheritance

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
}

class ChildClass extends ParentClass


{
// Additional properties and methods
}

Example
<?php
class Animal
{
public function eat()
{
echo "Animal is eating";
}
}

class Dog extends Animal


{
}

$dog = new Dog();

$dog->eat();
?>

Output:

Animal is eating

Here, the Dog class inherits the eat() method from the Animal class.

Types of Inheritance in PHP

PHP mainly supports the following types of inheritance.

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";
}
}

class Car extends Vehicle


{
}

$car = new Car();

$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";
}
}

class Dog extends Animal


{
}

class Puppy extends Dog


{
}

44
Web Technologies IV SEM BCA

$obj = new Puppy();

$obj->eat();
?>

Output:

Eating

Here:

Animal

Dog

Puppy

The Puppy class indirectly inherits the method from Animal.

3. Hierarchical Inheritance

In Hierarchical Inheritance, multiple child classes inherit from the same parent class.

Example
<?php
class Animal
{
public function eat()
{
echo "Eating";
}
}

class Dog extends Animal


{
}

class Cat extends Animal


{
}

$dog = new Dog();


$cat = new Cat();

$dog->eat();
?>

Output:

45
Web Technologies IV SEM BCA

Eating

Structure:

Animal
/ \
Dog Cat

Both child classes inherit from the same parent class.

4. Multiple Inheritance (Using Interfaces)

PHP does not support multiple inheritance through classes directly.

For example, the following is not allowed:

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.

Method overriding allows child classes to customize inherited behavior.

Example of Method Overriding

<?php
class Animal
{
public function sound()
{
echo "Animal makes sound";
}
}

class Dog extends Animal


{
public function sound()
{
echo "Dog barks";

46
Web Technologies IV SEM BCA

}
}

$dog = new Dog();

$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.

Advantages of Method Overriding

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.

5.15 Interface and Abstract Classes in PHP

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).

The child class must implement all abstract methods.

Example
<?php
abstract class Animal
{
abstract public function sound();
}

class Dog extends Animal


{
public function sound()
{
echo "Dog barks";
}
}

47
Web Technologies IV SEM BCA

$obj = new Dog();


$obj->sound();
?>

Output:

Dog barks

Key Points

 Declared using the abstract keyword.


 Cannot create objects directly.
 Can contain both abstract and normal methods.
 Child classes must implement abstract methods.

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.

A class implements an interface using the implements keyword.

Example
<?php
interface Animal
{
public function sound();
}

class Dog implements Animal


{
public function sound()
{
echo "Dog barks";
}
}

$obj = new Dog();


$obj->sound();
?>

Output:

Dog barks

Key Points

 Declared using the interface keyword.

48
Web Technologies IV SEM BCA

 Cannot create objects directly.


 Contains only method declarations.
 A class must implement all interface methods.
 Supports multiple inheritance through interfaces.

Difference Between Abstract Class and Interface

Abstract Class Interface

Uses abstract keyword Uses interface keyword

Can contain abstract and normal methods Contains only method declarations

Can have properties (variables) Cannot have normal properties

A class extends an abstract class A class implements an interface

Supports single inheritance Supports multiple inheritance

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.

5.16 Superglobals in PHP

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

Used to collect data sent through the URL.

$name = $_GET['name'];

$_POST

Used to collect data submitted through HTML forms.

$name = $_POST['name'];

49
Web Technologies IV SEM BCA

$_REQUEST

Contains data from both GET and POST methods.

$name = $_REQUEST['name'];

$_SERVER

Contains information about the server and current request.

echo $_SERVER['PHP_SELF'];

$_SESSION

Used to store user session data.

$_SESSION['username'] = "Ravi";

$_COOKIE

Used to store and retrieve cookies.

echo $_COOKIE['user'];

$_FILES

Used to handle file uploads.

$_FILES['file'];

$_GLOBALS

Contains all global variables of the script.

$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.

5.17 PHP Form Handling and Validation

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.

Form Handling in PHP

A form sends data to a PHP script using either the GET or POST method.

HTML Form Example


<form method="post" action="[Link]">
Name:
<input type="text" name="username">

<input type="submit" value="Submit">


</form>

When the user clicks the Submit button, the data is sent to [Link].

Processing Form Data Using POST


<?php
$name = $_POST['username'];

echo "Welcome " . $name;


?>

Output (if user enters Ravi):

Welcome Ravi

Here, the $_POST superglobal is used to retrieve the form data.

-> GET Method

The GET method sends data through the URL.

Example URL:

[Link]?username=Ravi

PHP code:

<?php
echo $_GET['username'];
?>

Output:

Ravi

51
Web Technologies IV SEM BCA

The GET method is suitable for non-sensitive information.

-> POST Method

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.

Without validation, users might submit:

Empty values
Invalid email addresses
Incorrect phone numbers
Special characters

Validation helps improve data quality and security.

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>

<input type="submit" value="Submit">


</form>

PHP Validation
<?php

$name = $_POST['name'];
$email = $_POST['email'];

if(empty($name))
{

52
Web Technologies IV SEM BCA

echo "Name is required";


}
elseif(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo "Invalid Email";
}
else
{
echo "Form Submitted Successfully";
}

?>

Output:

Form Submitted Successfully

If the entered data is valid, the form is processed successfully.

Advantages of Form Validation

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.

5.18 File Uploads, Cookies, Sessions, and Error Handling in PHP

File Uploads in PHP

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">

<input type="submit" value="Upload">


</form>

53
Web Technologies IV SEM BCA

PHP Script
<?php
move_uploaded_file(
$_FILES["myfile"]["tmp_name"],
"uploads/" . $_FILES["myfile"]["name"]
);

echo "File Uploaded Successfully";


?>

Output:

File Uploaded Successfully

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.

PHP provides the setcookie() function to create cookies.

Syntax
setcookie(name, value, expiry_time);

Example
<?php
setcookie("username", "Ravi", time()+3600);

echo "Cookie Created";


?>

Output:

Cookie Created

The cookie remains available for one hour.

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";

echo "Session Created";


?>

Output:

Session Created

Accessing Session Data


<?php
session_start();

echo $_SESSION["username"];
?>

Output:

Ravi

Destroying a Session
<?php
session_start();

session_destroy();
?>

This removes all session data.

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

Error Handling in PHP

Errors are problems that occur during the execution of a program. Error handling helps identify,
manage, and respond to these problems gracefully.

PHP provides several error-reporting functions and exception-handling mechanisms.

Common PHP Errors

 Parse Errors
 Fatal Errors
 Warning Errors
 Notice Errors

Example of an Error
<?php
echo $name;
?>

Since $name is not defined, PHP generates a notice.

Displaying Errors
<?php
error_reporting(E_ALL);
?>

This displays all errors and warnings.

Exception Handling

PHP uses try, catch, and throw for exception handling.

Example
<?php

try
{
throw new Exception("Something went wrong");
}
catch(Exception $e)
{
echo $e->getMessage();
}

?>

Output:

56
Web Technologies IV SEM BCA

Something went wrong

The try block contains code that may generate an exception. The catch block handles the
exception and displays the error message.

Advantages of Error Handling

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.

5.19 Connecting to a Database in PHP

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

 localhost → Database server


 root → Username
 "" → Password
 studentdb → Database name

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.

5.20 CRUD Operations in PHP with MySQL

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.

Assume a table named students:

id name course

1 Ravi BCA

1. Create (Insert Data)

The INSERT query is used to add new records to a table.

<?php

$conn = mysqli_connect("localhost","root","","studentdb");

$sql = "INSERT INTO students(name, course)


VALUES('Ravi','BCA')";

mysqli_query($conn, $sql);

echo "Record Inserted";

?>

Output:

58
Web Technologies IV SEM BCA

Record Inserted

2. Read (Retrieve Data)

The SELECT query is used to fetch records from a table.

<?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

3. Update (Modify Data)

The UPDATE query is used to modify existing records.

<?php

$conn = mysqli_connect("localhost","root","","studentdb");

$sql = "UPDATE students


SET course='BSc'
WHERE id=1";

mysqli_query($conn, $sql);

echo "Record Updated";

?>

Output:

Record Updated

59
Web Technologies IV SEM BCA

4. Delete (Remove Data)

The DELETE query is used to remove records from a table.

<?php

$conn = mysqli_connect("localhost","root","","studentdb");

$sql = "DELETE FROM students


WHERE id=1";

mysqli_query($conn, $sql);

echo "Record Deleted";

?>

Output:

Record Deleted

Summary of CRUD Operations

Operation SQL Command Purpose

Create INSERT Add new records

Read SELECT Retrieve records

Update UPDATE Modify existing records

Delete DELETE Remove records

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.

5.21 Prepared Statements and Bound Parameters in PHP

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);

echo "Record Inserted";

?>

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

"SELECT * FROM students LIMIT 5"


);

?>

This retrieves only the first 5 records.

Example with Starting Position


SELECT * FROM students LIMIT 2, 5;

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.

Getting the Last Inserted ID

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");

$sql = "INSERT INTO students(name, course)


VALUES('Ravi','BCA')";

mysqli_query($conn, $sql);

$last_id = mysqli_insert_id($conn);

echo "Last Inserted ID: " . $last_id;

?>

Output:

Last Inserted ID: 1


The value may vary depending on the records already present in the table.

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

You might also like