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

Theory of PHP Programming (5th Sem) .

Uploaded by

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

Theory of PHP Programming (5th Sem) .

Uploaded by

sahil gupta.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

THEORY FILE : Programming in PHP

(FULL NOTES: BY SAHIL RAUNIYAR) .

SUBJECT CODE: UGCA: 1929

BACHELOR OF COMPUTER APPLICATIONS

MAINTAINED BY: TEACHER’S /MAM’:

IL
Sahil Kumar Prof.

COLLEGE ROLL NO: 226617

UNIVERSITY ROLL NO: 2200315


H
SA

DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

BABA BANDA SINGH BAHADUR ENGINEERING

COLLEGE FATEGARH SAHIB


➖➖
1

Program BCA

Course Name ➖ Semester 5th.


Programming in PHP (Theory).

UNIT ➖01
Introduction to PHP

● Evolution of PHP & its comparison Interfaces to External systems ➖


PHP originally stood for "Personal Home Page" when it was first created by Rasmus Lerdorf
in 1995. However, as the language evolved and its usage expanded beyond personal web

IL
pages, the name was changed. Now, PHP stands for "PHP: Hypertext Preprocessor," which is
a recursive acronym.

PHP (Hypertext Preprocessor) has undergone significant evolution since its creation in 1995
by Rasmus Lerdorf. Here’s a summary of its key developments and how it compares to
interfaces with external systems:


Evolution of PHP

1. PHP/FI (1995) ➖
H
Initial release by Rasmus Lerdorf.
Simple set of Common Gateway Interface (CGI) binaries written in C.
Provided basic functionality for web development, such as form handling and database
SA
interaction.

2. PHP 3 (1997) ➖
Complete rewrite by Andi Gutmans and Zeev Suraski.
Introduced a more robust and extensible platform.
Added support for a wider range of databases and protocols.

3. PHP 4 (2000) ➖
Introduction of the Zend Engine 1.0, improving performance and reliability.
Enhanced session handling and output buffering.
Improved support for object-oriented programming (OOP).

4. PHP 5 (2004) ➖
Zend Engine II introduced.
Significant improvements in OOP capabilities (private/public/protected, abstract classes,
interfaces).
Introduction of SimpleXML, a more robust extension for XML manipulation.
Improved MySQL support with MySQLi.

2
5. PHP 5.3 (2009)
Added namespaces, late static binding, and lambda functions.
Introduction of the PDO (PHP Data Objects) extension for database access.

6. PHP 7 (2015) ➖
Major performance improvements (up to twice as fast as PHP 5.6).
Introduction of scalar type declarations and return type declarations.
Anonymous classes and improved error handling with throwable errors and exceptions.

7. PHP 8 (2020) ➖
Introduction of the Just-In-Time (JIT) compilation.
Union types, named arguments, attributes for metadata, and match expressions.
Enhancements to the type system and improvements in error handling.

IL
● Comparison to Interfaces with External Systems ➖
PHP’s evolution has significantly impacted how it interfaces with external systems:

1. Database Interfaces
H ➖
I. Early PHP (PHP/FI to PHP 4): Basic MySQL support with direct functions
(mysql_connect(), mysql_query()).

II. PHP 5: Introduction of MySQLi and PDO for a more flexible and secure database
interaction, supporting multiple databases (MySQL, PostgreSQL, SQLite, etc.).
III. PHP 7+: Continued improvements in database interfaces with better error handling,
SA
security, and performance.

2. Web Services and APIs ➖


I. PHP 4 and 5: Basic support for SOAP and XML-RPC for interacting with web services.
II. PHP 5+: Improved support for RESTful APIs using cURL and built-in functions. JSON
handling became more robust with the introduction of json_encode() and json_decode().
III. PHP 7+: Enhanced support for modern web service standards and improved
performance for API interactions.

3. File System and External Resources ➖


I. Early PHP: Basic file handling functions (fopen(), fread(), fwrite()).
II. PHP 5+: Introduction of the SPL (Standard PHP Library) providing more sophisticated
file handling and directory iteration.
III. PHP 7+: Continued enhancements in file system handling, including better support for
asynchronous operations.

3
4. Security Interfaces

I. PHP 4 and 5: Basic security features such as strip_tags(), htmlspecialchars(), and


addslashes().
II. PHP 5+: Improved security with functions like password_hash() and password_verify()
for password management.
III. PHP 7+: Stronger cryptographic capabilities and enhancements in secure coding
practices.

5. Interoperability with Other Languages :-

I. Early PHP: Limited to basic shell_exec calls and C extensions.


II. PHP 5+: Better support for COM and .NET (Windows), and interoperability with Java via

IL
extensions.
III. PHP 7+: Improved FFI (Foreign Function Interface) allowing calling functions from C
libraries directly in PHP scripts.

PHP’s growth from a simple scripting tool to a robust, high-performance language is evident.
Its ability to interface with external systems has also evolved, offering greater flexibility,
security, and performance for modern web development needs.


H
● Hardware and Software requirements

Here are some hardware and software requirements for PHP: ➖


1. Hardware Requirements ➖

SA
Minimum:
I. Processor: Dual-core processor (e.g., Intel Core i3 or AMD equivalent)
II. RAM: 4 GB
III. Storage: 100 GB HDD
IV. Monitor: 1024x768 resolution

Recommended: ➖
I. Processor: Quad-core processor (e.g., Intel Core i5 or AMD equivalent)
II. RAM: 8 GB or more
III. Storage: 256 GB SSD
IV. Monitor: Full HD (1920x1080) resolution or higher

2. Software Requirements ➖
Operating System:
Windows 7/8/10/11, macOS, or Linux (Ubuntu, Fedora, etc.)

Web Server :
I. Apache HTTP Server
4
II. Nginx

PHP:
I. PHP 7.4 or later (PHP 8.x recommended)

Database:
I. MySQL
II. PostgreSQL
III. SQLite
IV. MariaDB

Development Environment (IDE/Editor):


I. Visual Studio Code

IL
II. PHPStorm
III. Sublime Text
IV. NetBeans

Version Control:
I. Git (GitHub, GitLab, Bitbucket)
H
Dependencies and Package Management:
I. Composer

Optional Tools:
I. XAMPP or WAMP (for a complete local server environment on Windows)
II. MAMP (for macOS)
SA
III. Docker (for containerized development environments)
IV. Additional Libraries and Extensions

Common PHP Extensions:


I. cURL
II. mbstring
III. PDO
IV. OpenSSL
V. GD

Frameworks (if needed):


I. Laravel
II. Symfony
III. CodeIgniter
IV. Zend Framework

Web Browsers (for testing):**


I. Google Chrome
II. Mozilla Firefox
5
III. Microsoft Edge
IV. Safari (for macOS)

These requirements ensure a smooth PHP development experience, enabling you to work
efficiently on both small and large projects.

● PHP Scripting ➖
PHP (Hypertext Preprocessor) is a scripting language that's used for web development. It's
executed on the server and then translated into HTML code for the client-side, which is then
outputted by the web browser. PHP is open-source, free to download and use, and is available
on all major operating systems and web servers.

Here are some things to know about PHP scripting: ➖

IL
Structure
A PHP script is made up of a series of statements, which can be assignments, function calls,
loops, conditional statements, or empty statements. Statements usually end with a semicolon.

File structure
A PHP file is made up of HTML code, CSS code, JavaScript code, and PHP code. The file
H
extension for PHP is ".php".

** PHP scripting involves writing code that is executed on the server to create dynamic web
pages. PHP (Hypertext Preprocessor) is embedded within HTML, making it a powerful tool for
building interactive and data-driven websites. Here's a brief guide to get you started with PHP
scripting:**


SA
Basic PHP Script

1. PHP Tags:


PHP code is enclosed within <?php ... ?> tags.
Ex
<?php
echo "Hello, World!";
?>

2. Variables: :-\


Variables in PHP start with a $ sign.
Ex
<?php
$greeting = "Hello, World!";
echo $greeting;
?>

6
3. Data Types:
PHP supports various data types, including strings, integers, floats, arrays, objects, and


booleans.
Ex
<?php
$string = "Hello, World!";
$int = 10;
$float = 10.5;
$bool = true;
$array = array("one", "two", "three");
?>

● Basic PHP Development ➖

IL
Basic PHP development involves understanding the core concepts of the language, how to set
up a development environment, and how to write simple scripts. Here's a guide to get you
started with basic PHP development.

Setting Up a Development Environment ➖


1. Install a Local Server Environment: ➖
I.
II.
III.
H
Windows: Use XAMPP or WAMP.
macOS: Use MAMP.
Linux: Install Apache, MySQL, and PHP using a package manager (e.g., sudo apt install
apache2 mysql-server php on Ubuntu).

2. Verify Installation:
SA
I. Once installed, ensure your server is running. Open your web browser and navigate to
http://localhost. You should see a welcome page indicating that your server is running.

Writing Your First PHP Script ➖


1. Create a PHP File: ➖
In your server's root directory (e.g., htdocs for XAMPP, www for WAMP), create a new file
named index.php.

2. Write Basic PHP Code: ➖


Write Basic PHP Code:

<?php
echo "Hello, World!";
?>
Run the Script:

Open your web browser and navigate to http://localhost/index.php. You should see "Hello,
World!" displayed on the page.
7
PHP Basics

1. PHP Syntax:
Ex:->
<?php
// This is a single-line comment

/*
This is a multi-line comment
*/

// Output text
echo "Hello, World!";

IL
?>


2. Variables:
Ex
<?php
$name = "John";
$age = 25;

echo "Age: " . $age;


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



3. Data Types:
Ex
SA
<?php
$string = "Hello, World!";
$integer = 42;
$float = 3.14;
$boolean = true;
$array = array("Apple", "Banana", "Cherry");
$null = null;

echo $string;
?>



4. Conditional Statements:
Ex
<?php
$age = 18;

if ($age >= 18) {


echo "You are an adult.";
} else {
8
echo "You are a minor.";
}
?>



5. Loops:
Ex
<?php
// For loop
for ($i = 0; $i < 5; $i++) {
echo "The number is: $i <br>";
}

// While loop

IL
$i = 0;
while ($i < 5) {
echo "The number is: $i <br>";
$i++;
}

// Foreach loop (for arrays)


H
$fruits = array("Apple", "Banana", "Cherry");
foreach ($fruits as $fruit) {

}
echo $fruit . "<br>";

?>



SA
6. Functions:
Ex
<?php
function greet($name) {
return "Hello, " . $name . "!";
}

echo greet("John");
?>



7. Form Handling:
Ex
<!-- HTML Form -->
<form method="post" action="index.php">
Name: <input type="text" name="name">
<input type="submit">
</form>

<?php
9
// PHP Script to handle form data
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
echo "Hello, " . $name;
}
?>
Connecting to a Database
1. Create a MySQL Database and Table:

Sql

CREATE DATABASE testdb;


USE testdb;

IL
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL
);



2. PHP Script to Connect and Query the Database:
Ex
<?php
H
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
SA
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Perform a query
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
10
echo "0 results";
}

$conn->close();
?>

Tips for PHP Development ➖


1. Use Comments:
I. Comment your code to improve readability and maintainability.

2. Error Reporting:


I. Enable error reporting during development to help identify and fix issues.

IL
Ex
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>

3. Sanitise Input: ➖
H
I. Always sanitise and validate user input to prevent security vulnerabilities like SQL
injection and XSS.

4. Use Version Control: ➖


I. Use Git for version control to keep track of changes and collaborate with others.


SA
5. Explore Frameworks:
I. Once comfortable with basic PHP, consider using frameworks like Laravel or Symfony to
streamline development and follow best practices.

This guide covers the essentials to get you started with basic PHP development. As you
become more experienced, you can delve into advanced topics and tools to enhance your
PHP skills.

● Working of PHP scripts ➖


PHP scripts work by being executed on the server side and generating HTML (or other types
of output) that is sent to the client's web browser. Here's an overview of the process:

How PHP Scripts Work

1. Client Request:➖
I. A user makes a request to a web server by entering a URL in their web browser, clicking
a link, or submitting a form.
II. This request is sent to the server, typically as an HTTP GET or POST request.

11
2. Server Receives Request:
I. The web server (e.g., Apache or Nginx) receives the request and determines that the
requested file is a PHP script based on the file extension (.php).

3. PHP Interpreter: ➖
I. The server hands over the PHP file to the PHP interpreter.
II. The PHP interpreter processes the script, executing the PHP code line by line.

4. Script Execution: ➖
I. During execution, PHP can perform various operations such as database queries, file
manipulations, and conditional logic.
II. PHP code is used to generate HTML, interact with databases, handle form data, and
perform other server-side operations.

IL
5. Output Generation: ➖
I. The PHP script generates output, typically in the form of HTML, which is sent back to the
web server.
II. The web server then sends this HTML content as the response to the client's request.

6. Client Receives Response: ➖


H
I. The client's web browser receives the HTML response and renders it, displaying the
content to the user.

Key Points in PHP Script Execution ➖


I. Server-Side Execution: PHP code is executed on the server, not on the client's machine.
SA
II. Dynamic Content Generation: PHP can generate dynamic content based on user input,
database interactions, and other server-side operations.

III. Integration with HTML: PHP scripts often include HTML code, and PHP can be
embedded within HTML using <?php ?> tags.

IV. Error Handling: PHP scripts should include error handling to manage database
connection issues, query failures, and other potential errors.

V. Security: Always sanitise and validate user input to prevent security vulnerabilities like
SQL injection and cross-site scripting (XSS).

This overview explains the basic working of PHP scripts, highlighting the interaction between
the client, server, PHP interpreter, and the resulting dynamic content generation.

● Basic PHP syntax ➖


Here are some basic syntax elements of PHP, a general-purpose scripting language:
12
1. PHP script
A PHP script can be placed anywhere in a document and starts with <?php and ends with ?>.
The default file extension for PHP files is .php.

2. PHP commands
A basic PHP command includes a function, an action, and a semicolon to indicate the end of
the command. When building functions, you can use parentheses and parameters.

3. Comments
PHP has three types of comment syntax:
I. Block comments: Use /* */
II. Inline comments: Use // or #

IL
Shorthand version
To print something, you can use a shorthand version that's similar to php echo and then
whatever you want to echo. You can omit the semicolon because it's a one-liner.

Processing PHP
To process PHP, you need to enclose your PHP code block within the PHP opening and
closing tags. For example, you can assign a variable and then echo it out.

● PHP data types


H➖
PHP supports various data types, each with specific uses and behaviors. Understanding these
data types is fundamental to effective PHP programming.


SA
Here are the primary data types in PHP:

1. Scalar Types ➖
a. Integer:
Whole numbers without a decimal point.
Example:
<?php
$integer = 42;
echo $integer; // Output: 42
?>

b. Float (Double):
Numbers with a decimal point or in exponential form.
Example:
<?php
$float = 3.14;
echo $float; // Output: 3.14
13
?>
c. String:
A sequence of characters, enclosed in single quotes (') or double quotes (").
Example:
<?php
$string = "Hello, World!";
echo $string; // Output: Hello, World!
?>

d. Boolean:
Represents two possible values: true or false.
Example:
<?php

IL
$boolean = true;
echo $boolean; // Output: 1 (true is displayed as 1)
?>

2. Compound Types ➖
a. Array:

Example:
<?php
// Indexed array
H
A collection of values, which can be indexed numerically or associatively.

$array = array("Apple", "Banana", "Cherry");


echo $array[1]; // Output: Banana
SA
// Associative array
$assocArray = array("name" => "John", "age" => 30);
echo $assocArray["name"]; // Output: John
?>

b. Object:
An instance of a class, which can contain properties and methods.
Example:
<?php
class Person {
public $name;
public $age;

public function __construct($name, $age) {


$this->name = $name;
$this->age = $age;
}
14
public function introduce() {
return "My name is " . $this->name . " and I am " . $this->age . " years old.";
}
}

$person = new Person("John", 30);


echo $person->introduce(); // Output: My name is John and I am 30 years old.
?>

3. Special Types ➖
a. NULL:
Represents a variable with no value.

IL
Example:
<?php
$nullVar = null;
echo $nullVar; // Output: (empty output)
?>

b. Resource:

Example:
<?php
H
A special variable, holding a reference to an external resource (e.g., a database connection).

$conn = mysqli_connect("localhost", "username", "password", "database");


if ($conn) {
echo "Connection successful!";
SA
}
?>

4. Type Juggling and Type Casting ➖


Type Juggling: PHP automatically converts variables to the required type based on the


context.
Ex
<?php
$var = "10";
$sum = $var + 20; // $var is converted to an integer
echo $sum; // Output: 30
?>


Type Casting: Manually converting a variable from one type to another.
Ex
<?php
$var = "10";
$intVar = (int) $var; // Casting string to integer
15
echo $intVar; // Output: 10
?>

5. Checking Data Types ➖


PHP provides several functions to check the type of a variable:

I. is_int(): Checks if a variable is an integer.


II. is_float(): Checks if a variable is a float.
III. is_string(): Checks if a variable is a string.
IV. is_bool(): Checks if a variable is a boolean.
V. `is_array(): Checks if a variable is an array.
VI. is_object(): Checks if a variable is an object.
VII. is_null(): Checks if a variable is NULL.

IL
Ex ➖
<?php
$var = 42;
if (is_int($var)) {
echo "Variable is an integer.";
}
?>
H
These data types form the basis of variable handling and manipulation in PHP, and
understanding them is crucial for effective programming in PHP.


SA
● Displaying type information:



Testing for a specific data type
PHP has a number of functions to test for a specific data type in a variable:

I. gettype(): Returns the type of a variable as a string, such as boolean, integer, double,
string, array, object, resource, NULL, or unknown type. For example, `$type =
gettype($variable); echo $type;` will output integer if $variable is 10.

II. is_type(): A group of functions that return true if a variable is of a specific type. For
example, is_bool($value) returns true if $value is a boolean value.

III. var_dump(): Dumps information about a variable, including its type and value. For
example, var_dump($variable); will output string(5) "Hello" if $variable is "Hello".

IV. settype(): Type casts a variable in-place.

V. get_debug_type(): Retrieves the type of an expression.



16
● Changing type with Set type
The settype() function in PHP can be used to change the type of a variable from its current
type to a specified type. The syntax for the function is settype(variable, type).
where:
I. variable: Specifies the variable to convert
II. type: Possible types include boolean, integer, float, string, array, object, and null

The function returns true on success and false on failure. For example, the following code will
change the type of $foo from a string to an integer and the type of $bar from a boolean to a


string !
Ex
<?php
$var = "10";

IL
$intVar = (int) $var;
echo $intVar; // Output: 10
?>

● Operators ➖
In PHP, operators are special characters or combinations of characters that perform operations

1. Arithmetic Operators
H
on variables and values. They are categorized into several types:

Arithmetic operators are used to perform common arithmetic operations such as addition,
subtraction, multiplication, etc.
SA
I. + (Addition): Adds two values.
II. - (Subtraction): Subtracts one value from another.
III. * (Multiplication): Multiplies two values.
IV. / (Division): Divides one value by another.
V. % (Modulus): Returns the remainder of a division.
VI. ** (Exponentiation): Raises a number to the power of another.

2. Assignment Operators
Assignment operators are used to write values to variables.

I. =: Assigns a value to a variable.


II. +=: Adds and assigns a value to a variable.
III. -=: Subtracts and assigns a value to a variable.
IV. *=: Multiplies and assigns a value to a variable.
V. /=: Divides and assigns a value to a variable.
VI. %=: Modulus and assigns a value to a variable.
17
3. Comparison Operators
Comparison operators are used to compare two values.

I. ==: Equal to.


II. ===: Identical (equal and of the same type).
III. !=: Not equal to.
IV. <>: Not equal to.
V. !==: Not identical.
VI. >: Greater than.
VII. <: Less than.
VIII. >=: Greater than or equal to.
IX. <=: Less than or equal to.

IL
4. Increment/Decrement Operators
These operators are used to increment or decrement a variable's value.

I. ++$variable: Pre-increment (increments the value by 1, then returns the value).


II. $variable++: Post-increment (returns the value, then increments the value by 1).
III. --$variable: Pre-decrement (decrements the value by 1, then returns the value).
IV. $variable--: Post-decrement (returns the value, then decrements the value by 1).

5. Logical Operators
H
Logical operators are used to combine conditional statements.

I. && (and): True if both operands are true.


II. || (or): True if either operand is true.
SA
III. ! (not): True if the operand is false.
IV. xor: True if either operand is true, but not both.

6. String Operators
String operators are used to manipulate strings.

I. .: Concatenation (combines two strings).


II. .=: Concatenation assignment (appends the argument on the right to the argument on
the left).

7. Array Operators
Array operators are used to compare arrays.

I. +: Union (combines two arrays).


II. ==: Equality (true if the arrays have the same key/value pairs).
III. ===: Identity (true if the arrays have the same key/value pairs in the same order and of
the same types).
IV. !=: Inequality (true if the arrays are not equal).
V. <>: Inequality (true if the arrays are not equal).
18
VI. !==: Non-identity (true if the arrays are not identical).

8. Type Operators
Type operators are used to work with types.

I. instanceof: Checks if an object is an instance of a class.

9. Bitwise Operators
Bitwise operators are used to perform bit-level operations.

I. &: AND (sets each bit to 1 if both bits are 1).


II. |: OR (sets each bit to 1 if one of two bits is 1).
III. ^: XOR (sets each bit to 1 if only one of two bits is 1).

IL
IV. ~: NOT (inverts all the bits).
V. <<: Left shift (shifts bits to the left).
VI. >>: Right shift (shifts bits to the right).

10. Null Coalescing Operator


??: Returns the first operand if it exists and is not null; otherwise, it returns the second
operand.
H
These operators are fundamental in PHP programming and are used to manipulate data and
control the flow of programs.


SA
● Variable manipulation
The definition of a manipulated variable is a factor that is purposefully and specifically changed
by the experimenter. The manipulated variable is also called the independent variable or test
variable. Variables are manipulated, or altered on purpose, to identify cause and effect

☹️
relationships.
Like - increment, decrement data , string declaring and initialising and etc .

● Dynamic variables and Variable scope ➖


Dynamic Variables ➖
Dynamic variables in PHP are variables whose names are generated dynamically during the
execution of the script. This is done using variable variables, where the value of a variable is
used as the name of another variable.

Example of Dynamic Variables ➖


<?php
$varName = 'hello';
$$varName = 'world'; // Creates a variable named 'hello' with the value 'world'
19

echo $hello; // Outputs: world


?>

In this example:
I. $varName is a variable that holds the string 'hello'.
II. $$varName uses the value of $varName as the name of a new variable. This creates a
new variable named $hello with the value 'world'.

Variable Scope ➖
Variable scope refers to the context within which a variable is defined and accessible.

IL
PHP has several types of variable scopes:
1. Local Scope
2. Global Scope
3. Static Scope
4. Function Parameters

1. Local Scope

function.
Ex
<?php
H
Variables declared within a function have a local scope and are only accessible within that


function test() {
$localVar = "I'm local";
SA
echo $localVar; // Outputs: I'm local
}
test();
echo $localVar; // Error: Undefined variable
?>

2. Global Scope
Variables declared outside of any function have a global scope and are accessible from any


part of the script, except inside functions unless explicitly specified.
Ex
<?php
$globalVar = "I'm global";

function test() {
global $globalVar;
echo $globalVar; // Outputs: I'm global
}
test();
?>
20
The global keyword allows you to access a global variable inside a function.


Alternatively, you can use the $GLOBALS array:
Ex
<?php
$globalVar = "I'm global";

function test() {
echo $GLOBALS['globalVar']; // Outputs: I'm global
}
test();
?>

IL
3. Static Scope
Static variables maintain their values between function calls. They are initialized only once and


retain their values across multiple calls to the function.
Ex
<?php
function test() {
static $count = 0;

}
$count++;
echo $count;
H
test(); // Outputs: 1
test(); // Outputs: 2
SA
test(); // Outputs: 3
?>

4. Function Parameters
Function parameters are local to the function and are initialized with the arguments passed to


the function.
Ex
<?php
function greet($name) {
echo "Hello, $name!";
}

greet("Alice"); // Outputs: Hello, Alice!


?>

Summary
I. Dynamic Variables: Allow the creation of variable names dynamically during execution
using variable variables ($$ syntax).
21
II. Variable Scope: Defines where a variable can be accessed in a program.

III. Local Scope: Variables declared inside a function.

IV. Global Scope: Variables declared outside any function.

V. Static Scope: Variables that retain their value across function calls.

VI. Function Parameters: Variables passed to a function and local to that function.

VII. Understanding variable scope is crucial for managing data and state within your PHP
programs effectively.

IL
H
SA
22

UNIT ➖ 02
Control Statements ➖
● if() and elseif() condition Statement, The switch statement, Using the?


Operator, Using the while() Loop, The do while statement, Using the for()
Loop

Control statements allow you to direct the flow of execution in a PHP script based on
conditions or repetitive tasks.

IL
Here are some key control statements:

1. if and elseif Condition Statement ➖


The if statement is used to execute a block of code if a specified condition is true. The elseif


statement allows you to check multiple conditions.
Ex
<?php
$age = 20;

if ($age < 18) {


H
echo "You are a minor.";
} elseif ($age < 65) {
echo "You are an adult.";
SA
} else {
echo "You are a senior.";
}
?>

2. The switch Statement ➖


The switch statement is used to perform different actions based on different conditions. It is a
cleaner alternative to multiple if statements when checking a single variable against multiple


values.
Ex
<?php
$day = "Monday";

switch ($day) {
case "Monday":
echo "Start of the work week!";
break;
case "Friday":
echo "End of the work week!";
23
break;
case "Saturday":
case "Sunday":
echo "It's the weekend!";
break;
default:
echo "It's a regular day.";
}
?>

3. Using the Ternary Operator ? ➖


The ternary operator is a shorthand for if and else. It is used to assign a value based on a


condition.

IL
Ex
<?php
$isAdult = ($age >= 18) ? "Yes" : "No";
echo $isAdult; // Outputs: Yes if $age >= 18, otherwise No
?>

4. Using the while Loop ➖



Ex
<?php
$i = 0;
H
The while loop executes a block of code as long as the specified condition is true.

while ($i < 5) {


SA
echo $i;
$i++;
}
?>

5. The do...while Statement ➖


The do...while loop is similar to the while loop, but it executes the block of code at least once


before checking the condition.
Ex
<?php
$i = 0;

do {
echo $i;
$i++;
} while ($i < 5);
?>

24
6. Using the for Loop
The for loop is used when you know in advance how many times you want to execute a


statement or a block of statements.
Ex
<?php
for ($i = 0; $i < 5; $i++) {
echo $i;
}
?>

Summary ➖
I. if and elseif Statements: Used to execute code based on one or more conditions.

IL
II. switch Statement: Used to perform different actions based on different conditions for a
single variable.

III. Ternary Operator ?: A shorthand for if and else.

IV. while Loop: Executes a block of code as long as the condition is true.
H
V. do while Loop: Similar to while loop but guarantees execution of the code block at least
once.

VI. for Loop: Used for a known number of iterations.

These control statements are essential for directing the flow of execution and handling
SA
repetitive tasks in PHP programs.

Functions ➖
● Function definition, Creation, Returning values, Library Functions, User Defined


functions, Dynamic function, default arguments, Passing
arguments to a function by value

Functions are reusable blocks of code designed to perform a specific task. They help organise
code, avoid redundancy, and improve readability.

1. Function Definition and Creation ➖


A function in PHP is defined using the function keyword followed by the function name,
parentheses (which may contain parameters), and a block of code.


Syntax:
Ex
25
<?php
function functionName($parameter1, $parameter2) {
// Code to be executed
}
?>
Example:
php
Copy code
<?php
function greet($name) {
echo "Hello, $name!";
}

IL
greet("Alice"); // Outputs: Hello, Alice!
?>

2. Returning Values ➖
Functions can return values using the return statement.

Example: ➖
<?php
function add($a, $b) {

}
return $a + $b;
H
$result = add(5, 3); // $result is 8
SA
echo $result; // Outputs: 8
?>

3. Library Functions ➖
PHP comes with many built-in library functions that perform various tasks, such as string
manipulation, mathematical calculations, and array operations.

Example of Library Functions: ➖


<?php
echo strlen("Hello, World!"); // Outputs: 13
echo str_replace("World", "PHP", "Hello, World!"); // Outputs: Hello, PHP!
echo sqrt(16); // Outputs: 4
?>

4. User-defined Functions ➖
User-defined functions are those that developers create to perform specific tasks not covered
by PHP's built-in functions.

26
Example:
<?php
function multiply($a, $b) {
return $a * $b;
}

echo multiply(4, 5); // Outputs: 20


?>

5. Dynamic Function Calls ➖


PHP allows calling functions dynamically using variable functions. This is useful when the
function to be called is determined at runtime.

IL
Example:
<?php
function sayHello() {
echo "Hello, World!";
}

$functionName = 'sayHello';

?>

6. Default Arguments
H
$functionName(); // Outputs: Hello, World!


Functions can have parameters with default values, which are used if no argument is passed.


SA
Example:
<?php
function greet($name = "Guest") {
echo "Hello, $name!";
}

greet(); // Outputs: Hello, Guest!


greet("Alice"); // Outputs: Hello, Alice!
?>

7. Passing Arguments to a Function by Value ➖


By default, PHP passes function arguments by value, meaning the function gets a copy of the
variable. Modifications to the parameter inside the function do not affect the original variable.

Example: ➖
<?php
function increment($value) {
$value++;
echo $value; // Outputs: 6
27
}

$number = 5;
increment($number);
echo $number; // Outputs: 5
?>

Summary ➖
I. Function Definition and Creation: Functions are defined using the function keyword and
can have parameters.

II. Returning Values: Functions can return values using the return statement.

IL
III. Library Functions: PHP provides built-in functions for common tasks.

IV. User-defined Functions: Developers can create custom functions for specific tasks.

V. Dynamic Function Calls: Functions can be called dynamically using variable functions.

VI. Default Arguments: Functions can have parameters with default values.

VII.
H
Passing Arguments by Value: By default, arguments are passed by value, meaning the
function gets a copy of the variable.

VIII. Functions are essential for structuring and organising code, making it more maintainable
and reusable.
SA
String Manipulation ➖

● Formatting String for Presentation, Formatting String for Storage, Joining
and Splitting String, Comparing String

String manipulation in PHP involves various operations such as formatting strings for
presentation, storage, joining and splitting strings, and comparing strings.

Here's how you can perform these operations in PHP: -

1. Formatting String for Presentation ➖


To format strings for presentation, you often manipulate their appearance or structure to
enhance readability or visual appeal. PHP provides several functions and methods for
formatting strings:

28
Example:
<?php
$name = "Alice";
$age = 30;

// Using double quotes for variable interpolation


echo "Hello, $name! You are $age years old.";

// Using printf for formatted output


printf("Hello, %s! You are %d years old.", $name, $age);
?>

2. Formatting String for Storage ➖

IL
When formatting strings for storage, you might consider escaping special characters or
ensuring a specific encoding. Functions like addslashes() or database-specific functions can
be used for these purposes.

Example: ➖
<?php
$string = "It's a PHP example.";
H
// Escaping single quotes for storage
$escapedString = addslashes($string);
echo $escapedString; // Outputs: It\'s a PHP example.
?>


SA
3. Joining and Splitting String

a. Joining (Concatenation): ➖
You can concatenate strings using the . operator or implode() function for arrays.

Example: ➖
<?php
$firstName = "John";
$lastName = "Doe";

// Using concatenation
$fullName = $firstName . " " . $lastName;
echo $fullName; // Outputs: John Doe

// Using implode for joining array elements


$array = array('Hello', 'World!');
$joinedString = implode(' ', $array);
echo $joinedString; // Outputs: Hello World!
?>

29
b. Splitting (Explode):
To split a string into an array based on a delimiter, use the explode() function.

Example: ➖
<?php
$string = "apple,banana,orange";
$fruits = explode(",", $string);
print_r($fruits); // Outputs: Array ( [0] => apple [1] => banana [2] => orange )
?>

4. Comparing Strings ➖
PHP provides several functions for comparing strings, such as strcmp(), strcasecmp(), and
operators like ==, ===, !=, etc.

IL
Example: ➖
<?php
$string1 = "apple";
$string2 = "banana";

// Using strcmp for case-sensitive comparison

if ($result < 0) {
H
$result = strcmp($string1, $string2);

echo "$string1 is less than $string2.";


} elseif ($result > 0) {
echo "$string1 is greater than $string2.";
} else {
SA
echo "$string1 and $string2 are equal.";
}

// Using === for case-sensitive equality check


if ($string1 === $string2) {
echo "Strings are identical.";
} else {
echo "Strings are not identical.";
}
?>

Summary ➖
I. Formatting String for Presentation: Use interpolation or printf() for formatted output.

II. Formatting String for Storage: Use functions like addslashes() for escaping characters.

III. Joining and Splitting String: Use concatenation (.) or implode() for joining, and explode()
for splitting.
30
IV. Comparing Strings: Use functions like strcmp(), strcasecmp(), or operators (==, ===,
etc.) for comparison.

Understanding these operations allows you to effectively manipulate strings in PHP according
to different requirements, whether for presentation, storage, or comparison.

Array ➖

● Anatomy of an Array, Creating index based and Associative array,
Looping array using each() and foreach() loop

IL
Arrays in PHP are versatile data structures that can store multiple values under a single
variable name. They can be indexed numerically (index-based arrays) or by strings
(associative arrays).

1. Anatomy of an Array ➖
An array in PHP can contain a collection of elements. Each element can be accessed using its
index (numeric or string).

Example:
<?php

// Numeric array
H
$numericArray = array(10, 20, 30, 40, 50);
SA
// Associative array
$associativeArray = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);
?>

2. Creating Index-based and Associative Arrays ➖



Index-based Array:
Ex
<?php
$numericArray = array(10, 20, 30, 40, 50);
?>
In this example, $numericArray is an index-based array with elements 10, 20, 30, 40, 50.

31


3. Associative Array:
Ex
<?php
$associativeArray = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);
?>
In this example, $associativeArray is an associative array with keys "name", "age", and "city".

4. Looping through Arrays ➖


IL
a. Using foreach Loop:
The foreach loop is used to iterate over each element in an array.

Example with Index-based Array: ➖


<?php
$numericArray = array(10, 20, 30, 40, 50);
H
foreach ($numericArray as $value) {
echo "$value ";
}
// Outputs: 10 20 30 40 50
?>


SA
Example with Associative Array:
<?php
$associativeArray = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);

foreach ($associativeArray as $key => $value) {


echo "$key: $value ";
}
// Outputs: name: John age: 30 city: New York
?>

b. Using each Function (Deprecated in PHP 7.2): ➖


The each() function returns the current key-value pair from an array and advances the array
cursor.

32
Ex
<?php
$numericArray = array(10, 20, 30, 40, 50);

while ($element = each($numericArray)) {


echo $element['key'] . ' => ' . $element['value'] . "\n";
}
?>

Summary ➖
I. Anatomy of an Array: Arrays can store multiple elements accessed by index or key.

II. Creating Arrays: Use array() or [ ] syntax to create arrays.

IL
III. Index-based Arrays: Numerically indexed arrays store values accessed by numeric
indices.

IV. Associative Arrays: Associative arrays store key-value pairs.

V. Looping through Arrays:

01.

02.
H
foreach Loop: Iterates over each element in an array.

each() Function: Deprecated in PHP 7.2, returns current key-value pair.

Understanding these concepts allows you to effectively work with arrays in PHP, iterating
SA
through elements and accessing values based on keys or indices.
33

UNIT ➖ 03
Forms ➖
● Working with Forms, Super global variables, Super global array,
Importing user input, Accessing user input, Combine HTML and PHP
code, Using hidden fields, Redirecting the user.

It looks like you're interested in learning more about forms and how to work with them in PHP.
Here's a brief overview of each topic:

IL
1. Working with Forms: Forms in HTML allow users to input data which can be submitted
to a server for processing. They use attributes like action (where the form data is sent)
and method (how it's sent: GET or POST).

2. Super Global Variables: In PHP, $_GET and $_POST are super global arrays used to
collect form data sent with GET and POST methods, respectively. $_REQUEST
combines both.
H
3. Importing User Input: PHP scripts use super global arrays ($_GET, $_POST,
$_REQUEST) to import form data based on the method specified in the form.

4. Accessing User Input: After form submission, PHP accesses user input through keys
SA
corresponding to form field names in $_GET or $_POST.

5. Combine HTML and PHP Code: PHP code can be embedded within HTML using
<?php ... ?> tags to dynamically generate content or process form data.

6. Using Hidden Fields: <input type="hidden"> fields store data that is not displayed to
users but can be submitted with the form.

7. Redirecting the User: After processing form data, PHP can redirect users to another
page using header("Location: newpage.php"); or JavaScript (window.location).

If you have specific questions or need examples on any of these topics, feel free to ask!

34
Working with File and Directories

● Understanding file & directory, Opening and closing a file, Coping,


renaming and deleting a file, Working with directories, File Uploading &


Downloading. Generating Images with PHP: Basics computer Graphics,
Creating Image

Working with files and directories in PHP involves several essential tasks. Here's an overview
of each topic you mentioned:

1. Understanding Files and Directories: ➖


I. Files: In PHP, files are entities used to store data persistently. They can be text files,

IL
images, scripts, etc.

II. Directories: Also known as folders, directories are containers used to organize files
hierarchically on a file system.

2. Opening and Closing a File:


H ➖
I. You can open a file in PHP using functions like fopen(), which returns a file handle used
for subsequent file operations.

II. Use fclose() to close an opened file handle after you've finished working with it.

3. Copying, Renaming, and Deleting a File: ➖


SA
I. Use copy() to duplicate a file.

II. rename() is used to change the name of a file or move it to a different location.

III. unlink() deletes a file from the file system.

4. Working with Directories: ➖


I. mkdir() creates a new directory.

II. rmdir() removes an empty directory.

III. opendir() and closedir() are used to open and close a directory handle for reading its
contents.

IV. scandir() lists files and directories inside a specified path.



35
5. File Uploading and Downloading:

I. HTML forms with enctype="multipart/form-data" allow file uploads.

II. PHP handles uploaded files via $_FILES super global array.

III. Use move_uploaded_file() to save an uploaded file to a specified location.

6. Generating Images with PHP: Basics of Computer Graphics: ➖


I. PHP's GD library or ImageMagick extension allows dynamic creation and manipulation
of images.

IL
II. Functions like imagecreate(), imagecolorallocate(), imagestring(), etc., create and
manipulate images programmatically.

7. Creating Images: ➖
I. Use PHP GD functions (imagecreate(), imagecopy(), etc.) to generate images
dynamically.

II.
H
Common tasks include creating thumbnails, adding watermarks, or generating charts.

If you have specific questions about any of these topics or need examples, feel free to ask!
SA
36

UNIT ➖ 04
Database Connectivity with MySql ➖

● Introduction to RDBMS, Connection with MySql Database, Performing
basic database operation (DML) (Insert, Delete, Update, Select)

Certainly! Here's an overview of database connectivity with MySQL in PHP, covering RDBMS
concepts and basic operations (DML):

IL
1. Introduction to RDBMS
Relational Database Management Systems (RDBMS) organize data into structured tables
(relations) with rows (tuples) and columns (attributes). They ensure data integrity through
relationships defined by keys (primary, foreign).

2. Connection with MySQL Database ➖


To connect PHP with MySQL, you typically use the mysqli (MySQL Improved) or PDO (PHP
H
Data Objects) extension.

a. Using mysqli:

Program Ex ➖
$servername = "localhost";
SA
$username = "username";
$password = "password";
$dbname = "database_name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";



b. Using PDO:
Ex
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
37

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

Performing Basic Database Operations (DML)



a. Inserting Data

IL
Ex
$sql = "INSERT INTO table_name (column1, column2, column3)
VALUES ('value1', 'value2', 'value3')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

Ex➖
b. Updating Data
H

$sql = "UPDATE table_name SET column1='new_value' WHERE condition";
if ($conn->query($sql) === TRUE) {
SA
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}



c. Deleting Data :
Ex
$sql = "DELETE FROM table_name WHERE condition";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}



d. Selecting Data
Ex
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
38
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}

These examples cover the basics of connecting to a MySQL database from PHP and
performing basic DML operations (Insert, Delete, Update, Select). Replace username,
password, database_name, table_name, column1, etc., with your actual database credentials
and schema details.

IL
🙂😀
HAPPY ENDING BY : SAHIL RAUNIYAR /
PTU-CODER
H
SA
39

SOME PREVIOUS YEAR QUESTIONS PAPER OF PTU

PHP (5th SEM ) Dec2019.pdf

Note:
Attempt Five questions in all, by choosing any One question each from Units I-IV. Unit V is
compulsory

UNIT-I

IL
I (a) State the differences between static website and dynamic website development. (6)
(b) Discuss the various looping statements used in PHP with suitable example. (7)

II (a) How do you print the values of variables in PHP? (4)


(b) Discuss the if else statement and the conditional operators with suitable example. (4)
(c) Write a note on the file inclusion statements in PHP. (5)

UNIT-II
H
III How do you define a function in PHP? What is difference between formal and actual
arguments? What happens when there is argument mismatch during function call? Create
a PHP program which finds the factorial of number recursively using functions.
SA
(13)

IV (a) Write a PHP program to find the number of characters in the string. (6)
(b) Discuss the functions for Inspecting arrays. (7)

UNIT-III

V (a) Discuss the two methods used in HTTP to handle form data. (5)
(b) Write a PHP code to connect to database. (5)
(c) Write a note on super global arrays. (3)

VI How do you create a query in PHP? How do you fetch the dataset? Discuss the four
fetching functions in detail.
(13)

UNIT-IV

VII What are cookies? Why are they used? How do you create, read and delete a cookie? (13)
40

VIII (a) Discuss the PHP file permissions. (6)


(b) How is file opened and closed in PHP? Discuss the various file opening modes. (7)

UNIT-V

IX (a) How do you configure PHP environment? (2)

(b) How do you include PHP section in HTML page? (2)

(c) What are the various ways to represent multi line and single line comments in PHP? (2)

IL
(d) What is static variable? (2)

(e) How PHP supports editing of data with HTML form? (2)

(f) How do you increase the session expire time? (2)

(g) Name any two directory functions.


H ANSWERS OF THESE PDF ➖
UNIT-I
SA
I (a) Differences between static website and dynamic website development (6)

● Static Website:
○ Content remains fixed unless manually updated.
○ Written in HTML/CSS.
○ Limited interactivity and functionality.
○ Faster to develop and host.
● Dynamic Website:
○ Content is generated on-the-fly based on user interactions and
database queries.
○ Written in languages like PHP, Python, etc.
○ Interactive elements, user authentication, content management
systems (CMS), etc.
○ Requires server-side processing and often a database.
I (b) Looping statements used in PHP with examples (7)
41
PHP supports several looping constructs:

● for loop:

php
Copy code
for ($i = 0; $i < 5; $i++) {
echo $i . "<br>";
}

● while loop:

IL
php
Copy code
$i = 0;
while ($i < 5) {
echo $i . "<br>";
$i++;
}
H
● do-while loop:
SA
php
Copy code
$i = 0;
do {
echo $i . "<br>";
$i++;
} while ($i < 5);

● foreach loop (for iterating over arrays):

php
Copy code
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
echo $color . "<br>";
42
}

UNIT-II

III How to define a function in PHP? Difference between formal and actual arguments? What happens
during argument mismatch?

● Defining a function:

php
Copy code
function calculateFactorial($n) {

IL
if ($n <= 1) {
return 1;
} else {
return $n * calculateFactorial($n - 1);
}
}
H
● Formal vs. Actual Arguments:
○ Formal arguments: Parameters declared in the function definition
($n in the example).
SA
○ Actual arguments: Values passed to the function during its
invocation (5 in calculateFactorial(5)).
● Argument Mismatch: PHP throws a warning or error depending on the
severity of the mismatch (e.g., too few arguments).
IV (a) PHP program to find the number of characters in a string (6)
php
Copy code
$string = "Hello, World!";
$length = strlen($string);
echo "Number of characters: " . $length;

IV (b) Functions for inspecting arrays (7)

PHP provides several functions to inspect arrays:

● count(): Returns the number of elements in an array.


43
● array_keys(): Returns all the keys or a subset of the keys of an array.
● array_values(): Returns all the values of an array.
● in_array(): Checks if a value exists in an array.
● array_search(): Searches an array for a value and returns the
corresponding key if successful.

UNIT-III

V (a) Two methods used in HTTP to handle form data (5)

● GET: Sends form data in the URL query string ($_GET in PHP).
● POST: Sends form data in the body of the HTTP request ($_POST in
PHP).

IL
V (b) PHP code to connect to a database (5)

Using mysqli extension:

php
Copy code

$username = "username";
$password = "password";
H
$servername = "localhost";

$dbname = "database_name";
SA
$conn = new mysqli($servername, $username, $password,
$dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

V (c) Note on super global arrays (3)

Super global arrays like $_GET, $_POST, $_REQUEST, $_SESSION, $_COOKIE,


etc., are built-in PHP arrays that store data across different scopes, such as
user input, session data, etc.
VI Creating a query in PHP, fetching dataset, and discussing fetching functions (13)
44
● Creating a Query:

php
Copy code
$sql = "SELECT * FROM users WHERE id = 1";
$result = $conn->query($sql);

● Fetching Dataset:

php
Copy code

IL
// Using mysqli
while ($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"];
}

// Using PDO
H
foreach ($result as $row) {
echo "Name: " . $row["name"];
}
SA
● Fetching Functions:
○ fetch_assoc(): Returns an associative array.
○ fetch_array(): Returns an array with both numeric and
associative indices.
○ fetch_object(): Returns the next row as an object.
○ fetch_row(): Returns a numeric array of the current row.

UNIT-IV

VII What are cookies? Why are they used? How to create, read, and delete a cookie? (13)

● Cookies: Small pieces of data stored on the client's computer by the web
server.
● Usage: Used to track user sessions, store user preferences, etc.
● Creating a Cookie:

php
Copy code
45
setcookie("username", "John Doe", time() + 3600, "/");

● Reading a Cookie:

php
Copy code
echo $_COOKIE["username"];

● Deleting a Cookie:

php

IL
Copy code
setcookie("username", "", time() - 3600, "/");

VIII (a) PHP file permissions (6)

File permissions in PHP determine who can read, write, or execute a file.
H
They are managed by the file system and can be set using functions like
chmod().
VIII (b) Opening and closing files in PHP, various file opening modes (7)

● Opening a File:
SA
php
Copy code
$file = fopen("file.txt", "r") or die("Unable to open
file!");

● Closing a File:

php
Copy code
fclose($file);

● File Opening Modes:


○ "r": Read only.
○ "w": Write only (creates a new file or truncates an existing file).
46
○ "a": Append (writes to the end of the file).
○ "r+": Read and write.
○ "w+": Read and write (creates a new file or truncates an existing
file).

UNIT-V

IX (a) Configuring PHP environment (2)

Configure PHP settings in php.ini file, such as memory_limit,


error_reporting, etc.
IX (b) Including PHP in HTML page (2)

IL
php
Copy code
<?php include 'header.php'; ?>

IX (c) Ways to represent comments in PHP (2)


H
● Single-line comment: // This is a comment
● Multi-line comment:

php
Copy code
SA
/*
This is a
multi-line comment
*/

IX (d) Static variable in PHP (2)

Static variables retain their value between function calls.


IX (e) PHP support for editing data with HTML forms (2)

PHP processes form data using $_GET or $_POST super global arrays.
IX (f) Increasing session expire time (2)

Set session expiration time using session_set_cookie_params() or


session.gc_maxlifetime in php.ini.
47
IX (g) Directory functions in PHP (2)

● opendir(): Opens a directory handle.


● closedir(): Closes a directory handle.

These answers cover a broad range of PHP topics based on your structured
questions. If you need further clarification or more examples on any specific
topic, feel free to ask!

IL
H
SA
48

PHP (5th SEM ) Dec2020.pdf

● Write a PHP script to insert records in the student table within the
course database having fields-student-id, student name, student age
through Form and display records in table format.

Sure, I'll provide you with a PHP script to insert records into a student table in
the course database using a form and then display the records in a table format.

First, ensure you have the course database and student table set up. Here is

IL
the SQL statement to create the student table:

sql

CREATE DATABASE course;

USE course;
H
CREATE TABLE student (
student_id INT AUTO_INCREMENT PRIMARY KEY,
SA
student_name VARCHAR(255) NOT NULL,
student_age INT NOT NULL
);

Now, here is the PHP script:

php

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "course";

// Create connection
49
$conn = new mysqli($servername, $username, $password,
$dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Insert data if form is submitted


if ($_SERVER["REQUEST_METHOD"] == "POST") {

IL
$student_name = $_POST['student_name'];
$student_age = $_POST['student_age'];

$sql = "INSERT INTO student (student_name, student_age)


VALUES ('$student_name', '$student_age')";
H
if ($conn->query($sql) === TRUE) {
echo "New record created successfully<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
SA
}
}

// Retrieve and display records


$sql = "SELECT student_id, student_name, student_age FROM
student";
$result = $conn->query($sql);

?>

<!DOCTYPE html>
<html>
<head>
<title>Insert Student Records</title>
50
</head>
<body>

<h2>Insert Student Record</h2>


<form method="POST" action="<?php echo $_SERVER['PHP_SELF'];
?>">
<label for="student_name">Student Name:</label>
<input type="text" id="student_name" name="student_name"
required><br><br>
<label for="student_age">Student Age:</label>

IL
<input type="number" id="student_age" name="student_age"
required><br><br>
<input type="submit" value="Submit">
</form>

<h2>Student Records</h2>
<table border="1">
<tr>
H
<th>Student ID</th>
<th>Student Name</th>
SA
<th>Student Age</th>
</tr>
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>" . $row["student_id"] . "</td>
<td>" . $row["student_name"] . "</td>
<td>" . $row["student_age"] . "</td>
</tr>";
}
} else {
echo "<tr><td colspan='3'>No records
found</td></tr>";
51
}
$conn->close();
?>
</table>

</body>
</html>

Explanation:

IL
1. Database Connection: The script connects to the MySQL database using
the mysqli extension.
2. Form Submission Handling: When the form is submitted, the script checks
the request method and inserts the submitted data into the student table.
3. Retrieve and Display Records: After inserting data, the script retrieves all
records from the student table and displays them in an HTML table.
H
4. HTML Form: A simple HTML form is provided to input student_name and
student_age.

Usage:

1. Create the course database and student table using the provided SQL
SA
statements.
2. Save the PHP script in a file, e.g., student_form.php.
3. Run the script on a server with PHP and MySQL support.
4. Access the script via a web browser to insert and display student records.

● What is Database? How is PHP code connected to a database for


retrieving data set? Consider any suitable example.

A database is an organized collection of data that can be easily accessed,


managed, and updated. Databases are used to store information in a structured
way, making it easy to retrieve, insert, update, and delete data efficiently. They
can range from small, simple collections of data to large, complex systems used
by enterprises.
52
Types of Databases

1. Relational Databases: These use structured query language (SQL) and


store data in tables. Examples include MySQL, PostgreSQL, Oracle, and
SQL Server.
2. NoSQL Databases: These are used for large sets of distributed data and
include document stores (e.g., MongoDB), key-value stores (e.g., Redis),
and column stores (e.g., Cassandra).
3. In-Memory Databases: These store data in the system's main memory
(RAM) for faster access. Examples include Redis and Memcached.

Connecting PHP to a Database

IL
To connect PHP to a database and retrieve data, we typically use a relational
database like MySQL. PHP provides several extensions to interact with
databases, such as mysqli and PDO.

Example: Connecting PHP to a MySQL Database

Here is a step-by-step guide and example of how to connect PHP to a MySQL


H
database, execute a query, and retrieve data.

1. Create a Database and Table

First, create a database and a table. For example, let's create a database called
school and a table called students.
SA
sql

CREATE DATABASE school;

USE school;

CREATE TABLE students (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(255) NOT NULL,

age INT NOT NULL


53
);

2. Insert Sample Data

sql

INSERT INTO students (name, age) VALUES ('John Doe', 20),


('Jane Smith', 22), ('Sam Brown', 19);

IL
3. PHP Script to Connect and Retrieve Data

php

Copy code

<?php
H
$servername = "localhost";

$username = "username"; // replace with your database


username

$password = "password"; // replace with your database


SA
password

$dbname = "school";

// Create connection

$conn = new mysqli($servername, $username, $password,


$dbname);

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);


54
}

// Retrieve data

$sql = "SELECT id, name, age FROM students";

$result = $conn->query($sql);

?>

IL
<!DOCTYPE html>

<html>

<head>
H
<title>Student Records</title>

</head>
SA
<body>

<h2>Student Records</h2>

<table border="1">

<tr>

<th>ID</th>

<th>Name</th>

<th>Age</th>

</tr>

<?php
55
if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {

echo "<tr>

<td>" . $row["id"] . "</td>

<td>" . $row["name"] . "</td>

<td>" . $row["age"] . "</td>

</tr>";

IL
}

} else {

echo "<tr><td colspan='3'>No records


found</td></tr>";

}
H
$conn->close();

?>
SA
</table>

</body>

</html>

Explanation:

1. Database Connection:
○ The PHP script connects to the MySQL database using the mysqli
extension.
○ Replace username and password with your MySQL credentials.
2. SQL Query Execution:
56
○ The script executes an SQL query to select all records from the
students table.
3. Data Retrieval:
○ The while loop fetches each row from the result set and displays it in
an HTML table.
4. HTML Output:
○ The data is displayed in an HTML table format on a web page.

Summary

A database is essential for storing and managing data. Connecting PHP to a


database involves creating a connection using appropriate credentials, executing

IL
SQL queries to retrieve data, and displaying that data in a readable format. The
mysqli extension in PHP provides a straightforward way to interact with MySQL
databases.

● What are cookies? How can you create, access and delete a cookies in
H
PHP with the help of an example ? Also differentiate between a session
and Cookie.

Cookies are small pieces of data stored on the user's computer by the web
browser while browsing a website. They are used to remember information about
the user, such as login details, preferences, and other data that can be retrieved
SA
later during subsequent visits to the same site.

Creating, Accessing, and Deleting Cookies in PHP

1. Creating a Cookie

To create a cookie in PHP, you use the setcookie() function. The basic syntax
is:

php

setcookie(name, value, expire, path, domain, secure,


httponly);

● name: The name of the cookie.


● value: The value of the cookie.
57
● expire: The expiration time (in seconds since the Unix epoch). If omitted or
set to 0, the cookie will expire at the end of the session (when the browser
closes).
● path: The path on the server where the cookie will be available.
● domain: The (sub)domain that the cookie is available to.
● secure: Indicates if the cookie should only be transmitted over a secure
HTTPS connection.
● httponly: When true, the cookie will be made accessible only through the
HTTP protocol (not accessible via JavaScript).

Example of Creating a Cookie:

IL
php

<?php

// Create a cookie that expires in 1 hour

setcookie("user", "John Doe", time() + 3600, "/");

?>
H
2. Accessing a Cookie
SA
Cookies can be accessed using the $_COOKIE superglobal array.

Example of Accessing a Cookie:

php

<?php

if (isset($_COOKIE["user"])) {

echo "User is: " . $_COOKIE["user"];

} else {

echo "User cookie is not set.";

?>
58

3. Deleting a Cookie

To delete a cookie, you set its expiration time to a past date.

Example of Deleting a Cookie:

php

<?php

// Delete the cookie by setting its expiration time to a


past date

IL
setcookie("user", "", time() - 3600, "/");

?>
H
Example: Full Cookie Handling Script

php

<?php

// Create a cookie
SA
setcookie("user", "John Doe", time() + 3600, "/");

// Access the cookie

if (isset($_COOKIE["user"])) {

echo "User is: " . $_COOKIE["user"];

} else {

echo "User cookie is not set.";

}
59
// Delete the cookie

setcookie("user", "", time() - 3600, "/");

?>

Difference Between Sessions and Cookies

Aspect Cookies Sessions

IL
Storage Stored on the client-side Stored on the server-side,
Location (user's browser). with a session ID stored
on the client-side.

Security Less secure, as data is More secure, as data is


H
stored on the client-side and
can be accessed or
manipulated by the user.
stored on the server-side
and less accessible to the
user.

Lifetime Can persist for a long time, Typically last until the
SA
depending on the expiration browser is closed, unless
time set. explicitly configured to last
longer.

Data Limited by the browser Can store larger amounts


Capacity (usually around 4KB per of data since it’s on the
cookie). server-side.

Accessibi Can be accessed by both Only accessible by the


lity the client (via JavaScript) server.
and server (via PHP).
60

Usage Remembering user Managing user login


Examples preferences, login sessions, storing
information, tracking user temporary data, tracking
activity across sessions. user activity within a
session.

Example: Using Sessions in PHP

Starting a Session and Storing Data:

php

IL
<?php

session_start(); // Start the session

$_SESSION["user"] = "John Doe";

?>
H
Accessing Session Data:

php
SA
Copy code

<?php

session_start(); // Continue the session

if (isset($_SESSION["user"])) {

echo "User is: " . $_SESSION["user"];

} else {

echo "User session is not set.";

?>
61

Deleting Session Data:

php

Copy code

<?php

session_start(); // Continue the session

session_unset(); // Remove all session variables

IL
session_destroy(); // Destroy the session

?>

In summary, cookies and sessions are both used to store user information, but
H
they differ in their storage location, security, lifetime, data capacity, and use cases.
Cookies are stored on the client-side and can persist for long periods, while
sessions are stored on the server-side and typically last for the duration of the
user's visit.
SA
● Write a PHP script to open, close, read and write data into a file. Also
describe various file permissions.

PHP Script to Open, Close, Read, and Write Data into a File

Here is a PHP script demonstrating how to open, close, read, and write data into a
file:

php

<?php

$file = 'example.txt';

// Open a file for writing


62
$handle = fopen($file, 'w') or die('Cannot open file:
'.$file);

// Write data to the file

$data = "Hello, World!\n";

fwrite($handle, $data);

IL
// Close the file

fclose($handle);

// Open the file for reading


H
$handle = fopen($file, 'r') or die('Cannot open file:
'.$file);
SA
// Read and display the file content

echo "File content:\n";

while (($line = fgets($handle)) !== false) {

echo $line;

// Close the file

fclose($handle);

?>
63

Explanation:

1. Opening a File:
○ fopen($file, 'w'): Opens the file for writing. If the file does not
exist, it creates it. If it exists, it truncates (empties) the file.
○ fopen($file, 'r'): Opens the file for reading. The file must exist.
2. Writing to a File:
○ fwrite($handle, $data): Writes the specified data to the file.
3. Reading from a File:
○ fgets($handle): Reads a line from the file. It reads until it reaches a

IL
newline character or the end of the file.
4. Closing a File:
○ fclose($handle): Closes the opened file.

Various File Permissions

File permissions define who can read, write, or execute a file. They are usually
H
represented as octal values.

Sym Octal Description


bol Value
SA
r 4 Read
permission

w 2 Write
permission

x 1 Execute
permission

Permissions are set for the file owner, the group, and others.

● rwxr-xr-- (Symbolic)
● 0754 (Octal)
64
This example means:

● The owner can read, write, and execute (7).


● The group can read and execute (5).
● Others can read (4).

Setting File Permissions in PHP

Use the chmod() function to set file permissions:

php

<?php

IL
$file = 'example.txt';

// Set permissions to read, write, and execute for the


owner, and read and execute for others

chmod($file, 0755);

?>
H
SA
Summary

● Opening a File: Use fopen().


● Writing to a File: Use fwrite().
● Reading from a File: Use fgets().
● Closing a File: Use fclose().
● File Permissions: Set using chmod(), represented as octal values.

Here's the complete example demonstrating opening, closing, reading, writing,


and setting file permissions:

php

<?php

$file = 'example.txt';
65

// Open a file for writing

$handle = fopen($file, 'w') or die('Cannot open file:


'.$file);

// Write data to the file

$data = "Hello, World!\n";

IL
fwrite($handle, $data);

// Close the file

fclose($handle);
H
// Set file permissions to read, write, and execute for the
owner, and read and execute for others
SA
chmod($file, 0755);

// Open the file for reading

$handle = fopen($file, 'r') or die('Cannot open file:


'.$file);

// Read and display the file content

echo "File content:\n";

while (($line = fgets($handle)) !== false) {

echo $line;
66
}

// Close the file

fclose($handle);

?>

This script covers the essential file operations and demonstrates how to manage
file permissions in PHP.

IL
● Write short answers of the following ➖
I. What is the use of === operator?
II. Explain the difference between $message and $$message.
III. What is the purpose of the super global variable called $_SERVER?
IV. What is the difference between include and require?
H
V. How a page is redirected in PHP?
VI. Name and explain the function used to delete a file from the system.
VII. How can the execution of a PHP script be stopped?
SA
What is the use of === operator?

The === operator in PHP is a strict comparison operator. It checks both the value
and the type of the variables being compared. This means that the comparison
will only return true if the values and types are identical.

php

<?php

$a = 42; // integer

$b = "42"; // string

var_dump($a == $b); // true, because values are equal

var_dump($a === $b); // false, because types are different


67
?>

Explain the difference between $message and $$message.

● $message is a regular variable that holds a value.


● $$message is a variable variable. It uses the value of $message as the
name of the variable it references.

php

<?php

$message = "greeting";

IL
$$message = "Hello, World!";

echo $greeting; // Outputs: Hello, World!

?>
H
What is the purpose of the super global variable called $_SERVER?

$_SERVER is a PHP super global variable that contains information about


headers, paths, and script locations. It provides details about the server and
execution environment.
SA
php

<?php

echo $_SERVER['PHP_SELF']; // Returns the filename of the


currently executing script

echo $_SERVER['SERVER_NAME']; // Returns the name of the


server host

?>

What is the difference between include and require?

● include and require are both used to include and evaluate a specified
file.
● If the file is not found, include generates a warning but the script continues
execution.
68
● If the file is not found, require generates a fatal error and stops the script
execution.

php

<?php

include 'non_existing_file.php'; // Generates a warning,


script continues

require 'non_existing_file.php'; // Generates a fatal error,


script stops

IL
?>
How is a page redirected in PHP?

A page can be redirected in PHP using the header() function. The Location
header is used to specify the URL to redirect to.

php

<?php
H
header("Location: http://www.example.com");
SA
exit(); // Ensure no further code is executed after
redirection

?>
Name and explain the function used to delete a file from the system.

The unlink() function is used to delete a file from the filesystem.

php

<?php

$file = 'example.txt';

if (file_exists($file)) {

unlink($file); // Deletes the file


69
echo "File deleted successfully.";

} else {

echo "File does not exist.";

?>
How can the execution of a PHP script be stopped?

The execution of a PHP script can be stopped using the exit() or die()

IL
functions. Both functions output a message and terminate the script.

php

<?php

echo "This is executed.";


H
exit("Script execution stopped."); // Stops script execution

echo "This will not be executed."; // This line will not be


executed
SA
?>

die() is an alias of exit(), and they can be used interchangeably.


70

PHP (5th SEM ) Dec2021.pdf

● How are functions created and invoked in PHP? Write a PHP functions that finds
the sum of N even numbers.
● How is recursion used in PHP? Explain with suitable example.

Creating and Invoking Functions in PHP

In PHP, functions are created using the function keyword followed by the function name, a
pair of parentheses (), and a block of code enclosed in curly braces {}. Functions are
invoked by calling their name followed by parentheses, optionally passing arguments.

IL
Syntax for Creating a Function
php
<?php
function functionName() {
// Code to be executed
}
?>
H
Syntax for Invoking a Function
php
<?php
SA
functionName(); // Call the function
?>

Example: Function to Find the Sum of N Even Numbers

Here's a PHP function that calculates the sum of the first N even numbers:

php
<?php
function sumEvenNumbers($n) {
$sum = 0;
for ($i = 1; $i <= $n; $i++) {
$sum += $i * 2;
}
return $sum;
}
71
// Example usage
$n = 5;
echo "The sum of the first $n even numbers is: " .
sumEvenNumbers($n);
?>

Using Recursion in PHP

Recursion is a programming technique where a function calls itself to solve smaller instances
of the same problem. In PHP, recursion is used similarly to other programming languages.

Example: Factorial Calculation Using Recursion

IL
The factorial of a number n is the product of all positive integers less than or equal to n. It is
denoted as n!. The factorial of n can be defined recursively as:

I. 0! = 1
II. n! = n * (n-1)! for n > 0

Here's a PHP function to calculate the factorial of a number using recursion:

php
<?php
function factorial($n) {
H
if ($n === 0) {
return 1; // Base case: 0! = 1
SA
} else {
return $n * factorial($n - 1); // Recursive case
}
}

// Example usage
$number = 5;
echo "The factorial of $number is: " . factorial($number);
?>

Explanation of Recursion Example

1. Base Case: The base case is the condition that stops the recursion. In the factorial
example, the base case is 0! = 1.
2. Recursive Case: The function calls itself with a smaller problem, n - 1, until it reaches
the base case.
72
Summary

I. Creating and Invoking Functions: Functions in PHP are created using the function
keyword and invoked by calling their name followed by parentheses.
II. Example of Sum of N Even Numbers: A function sumEvenNumbers($n) calculates
the sum of the first N even numbers.
III. Using Recursion: Recursion is a technique where a function calls itself to solve smaller
instances of the same problem. The factorial example demonstrates how to use
recursion to calculate the factorial of a number.

IL
● Explain the syntax and usage of Multidimensional Arrays in PHP. Give examples.
● Explain the syntax and usage of any three string functions.

Multidimensional Arrays in PHP

A multidimensional array is an array that contains one or more arrays. PHP supports
H
multidimensional arrays that can be either indexed or associative arrays. These arrays can be
used to store complex data structures.

Syntax

The syntax for defining a multidimensional array is as follows:


SA
php

$array = array(

array(element1, element2, element3),

array(element4, element5, element6),

// more arrays

);

Usage

To access elements in a multidimensional array, you use multiple indices.

Example: Indexed Multidimensional Array

php

<?php
73
$students = array(

array("John", "Doe", 20),

array("Jane", "Smith", 22),

array("Sam", "Brown", 19)

);

// Accessing elements

IL
echo "Name: " . $students[0][0] . " " . $students[0][1] . ", Age: " .
$students[0][2] . "\n";

echo "Name: " . $students[1][0] . " " . $students[1][1] . ", Age: " .
$students[1][2] . "\n";

echo "Name: " . $students[2][0] . " " . $students[2][1] . ", Age: " .
$students[2][2] . "\n";

?>
H
Example: Associative Multidimensional Array
SA
php

<?php

$students = array(

"student1" => array("firstName" => "John", "lastName" => "Doe",


"age" => 20),

"student2" => array("firstName" => "Jane", "lastName" => "Smith",


"age" => 22),

"student3" => array("firstName" => "Sam", "lastName" => "Brown",


"age" => 19)

);
74
// Accessing elements

echo "Name: " . $students["student1"]["firstName"] . " " .


$students["student1"]["lastName"] . ", Age: " .
$students["student1"]["age"] . "\n";

echo "Name: " . $students["student2"]["firstName"] . " " .


$students["student2"]["lastName"] . ", Age: " .
$students["student2"]["age"] . "\n";

echo "Name: " . $students["student3"]["firstName"] . " " .


$students["student3"]["lastName"] . ", Age: " .
$students["student3"]["age"] . "\n";

IL
?>

String Functions in PHP

PHP provides a wide range of string functions to manipulate strings. Here are three commonly
used string functions:

1. strlen()
H
The strlen() function returns the length of a string.

Syntax:
SA
php

strlen(string);

Example:

php

<?php

$str = "Hello, World!";

echo "The length of the string is: " . strlen($str); // Outputs: 13

?>

2. str_replace()
75
The str_replace() function replaces all occurrences of a search string with a replacement
string.

Syntax:

php

str_replace(search, replace, subject);

Example:

php

Copy code

IL
<?php

$str = "Hello, World!";

$newStr = str_replace("World", "PHP", $str);

echo $newStr; // Outputs: Hello, PHP!

?>

3. strpos()
H
The strpos() function finds the position of the first occurrence of a substring in a string. It
returns the index of the first occurrence or false if the substring is not found.
SA
Syntax:

php

strpos(haystack, needle);

Example:

php

<?php

$str = "Hello, World!";

$position = strpos($str, "World");

if ($position !== false) {

echo "The position of 'World' in the string is: " . $position; //


Outputs: 7
76
} else {

echo "'World' not found in the string.";

?>

Summary

I. Multidimensional Arrays: Used to store complex data structures in PHP. They can be
either indexed or associative arrays.
II. String Functions:
A. strlen(): Returns the length of a string.

IL
B. str_replace(): Replaces occurrences of a search string with a replacement
string.
C. strpos(): Finds the position of the first occurrence of a substring in a string.

● How are HTML Form controls connected to a database in PHP? Consider any
H
suitable example to explain.

Connecting HTML form controls to a database in PHP involves several steps. Here's a
step-by-step guide with an example:
SA
1. Create an HTML Form: The form collects user input.
2. Process Form Data with PHP: Retrieve the input data using PHP.
3. Connect to a Database: Use PHP to connect to a database.
4. Insert Form Data into the Database: Use SQL to insert the form data into a database
table.

Example: HTML Form Connected to a Database

Step 1: Create an HTML Form

html

Copy code

<!DOCTYPE html>

<html>

<head>

<title>Student Registration</title>
77
</head>

<body>

<h2>Student Registration Form</h2>

<form action="process_form.php" method="post">

<label for="student_id">Student ID:</label>

<input type="text" id="student_id" name="student_id"


required><br><br>

<label for="student_name">Student Name:</label>

IL
<input type="text" id="student_name" name="student_name"
required><br><br>

<label for="student_age">Student Age:</label>

<input type="number" id="student_age" name="student_age"


required><br><br>
H
<input type="submit" value="Submit">

</form>

</body>
SA
</html>

Step 2: Process Form Data with PHP

Create a file named process_form.php to handle the form submission.

php

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

// Retrieve form data

$student_id = $_POST['student_id'];

$student_name = $_POST['student_name'];
78
$student_age = $_POST['student_age'];

// Step 3: Connect to the Database

$servername = "localhost";

$username = "root"; // Replace with your database username

$password = ""; // Replace with your database password

$dbname = "course"; // Replace with your database name

IL
// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
H
if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

// Step 4: Insert Form Data into the Database


SA
$sql = "INSERT INTO student (student_id, student_name,
student_age) VALUES ('$student_id', '$student_name',
'$student_age')";

if ($conn->query($sql) === TRUE) {

echo "New record created successfully";

} else {

echo "Error: " . $sql . "<br>" . $conn->error;

$conn->close();
79
} ?>

Explanation:

1. HTML Form: The form collects the student's ID, name, and age.
2. Process Form Data: The process_form.php script retrieves the form data using the
$_POST superglobal array.
3. Connect to Database: The script creates a connection to the MySQL database using
the mysqli class.
4. Insert Data: The script inserts the form data into the student table using an SQL
INSERT query.

Database Table Structure

IL
Before running the example, make sure you have a MySQL database named course with a
table named student. The table should have the following structure:

sql

Copy code

CREATE DATABASE course;


H
USE course;
SA
CREATE TABLE student (

student_id INT(11) NOT NULL,

student_name VARCHAR(50) NOT NULL,

student_age INT(3) NOT NULL,

PRIMARY KEY (student_id)

);

Complete Workflow

1. Fill out the HTML form: The user enters their student ID, name, and age.
2. Submit the form: The form data is sent to process_form.php via POST method.
3. Process the form data:
80
○ The PHP script retrieves the submitted data.
○ It establishes a connection to the MySQL database.
○ The script inserts the form data into the student table.
○ It provides feedback on whether the insertion was successful or if there was an
error.

This example demonstrates a basic implementation of connecting HTML form controls to a


database in PHP, handling data insertion securely and efficiently.

● Write SQL queries to fetch, edit and delete records in a dataset of an employee

IL
table having fields-empcode, ename, dob, qualifications and salary.

SQL Queries for the Employee Table

Assuming we have an employee table with the fields empcode, ename, dob,
qualifications, and salary, here are the SQL queries to fetch, edit, and delete records.

Table Structure

sql
H
CREATE TABLE employee (
SA
empcode INT PRIMARY KEY,

ename VARCHAR(100),

dob DATE,

qualifications VARCHAR(255),

salary DECIMAL(10, 2)

);

1. Fetch Records

To fetch all records from the employee table:

sql

SELECT * FROM employee;

To fetch specific columns:


81
sql

SELECT empcode, ename, salary FROM employee;

To fetch records with a condition (e.g., salary greater than 50000):

sql

SELECT * FROM employee WHERE salary > 50000;

To fetch a specific employee by empcode:

sql

SELECT * FROM employee WHERE empcode = 101;

IL
2. Edit (Update) Records

To update the salary of a specific employee:

sql

UPDATE employee

SET salary = 60000

WHERE empcode = 101;


H
To update multiple fields (e.g., ename and qualifications):
SA
sql

UPDATE employee

SET ename = 'John Doe', qualifications = 'MBA'

WHERE empcode = 102;

3. Delete Records

To delete a specific employee record by empcode:

sql

DELETE FROM employee

WHERE empcode = 103;

To delete all employees with a salary less than 30000:

sql
82
DELETE FROM employee

WHERE salary < 30000

Summary of SQL Queries

Here are all the queries in one place for easy reference:

Fetch All Records

sql

SELECT * FROM employee;

Fetch Specific Columns

IL
sql

SELECT empcode, ename, salary FROM employee;

Fetch Records with a Condition

sql
H
SELECT * FROM employee WHERE salary > 50000;

Fetch a Specific Employee by empcode

sql

SELECT * FROM employee WHERE empcode = 101;


SA
Update Salary of a Specific Employee

sql

UPDATE employee

SET salary = 60000

WHERE empcode = 101;

Update Multiple Fields of a Specific Employee

Sql

UPDATE employee

SET ename = 'John Doe', qualifications = 'MBA'

WHERE empcode = 102;


83
Delete a Specific Employee Record by empcode

sql

DELETE FROM employee

WHERE empcode = 103;

Delete All Employees with Salary Less Than a Specific Amount

sql

DELETE FROM employee

WHERE salary < 30000;

IL
These queries cover the basic operations for fetching, updating, and deleting records in a
dataset of an employee table.

● What do you understand by Cookies? Create a cookie named “user” with the
H
value “Sushma Kohli” that expires after 15 days. How will this cookie be available
on the entire website? Also write code to retrieve it in PHP?

● What is a Session? Write PHP Code to show all the session variable values for a
SA
user session.

Understanding Cookies

Cookies are small pieces of data stored on the client-side (in the user's browser) and are used
to track and identify returning users. They are useful for maintaining user preferences, login
sessions, and other personalised settings across multiple pages of a website.

Creating and Retrieving Cookies

Creating a Cookie

To create a cookie in PHP, use the setcookie() function. Here's how to create a cookie
named "user" with the value "Sushma Kohli" that expires after 15 days:

php

<?php
84
// Calculate the expiration time (current time + 15 days)

$expiryTime = time() + (15 * 24 * 60 * 60); // 15 days in seconds

// Create the cookie

setcookie("user", "Sushma Kohli", $expiryTime, "/");

?>

IL
● "/" indicates that the cookie is available across the entire website.

Retrieving a Cookie

To retrieve the value of the "user" cookie in PHP:

php

<?php
H
if (isset($_COOKIE['user'])) {

echo "User: " . $_COOKIE['user'];

} else {
SA
echo "Cookie 'user' is not set.";

?>

Understanding Sessions

Sessions are used to store information about a user across multiple pages of a website during
their visit. Unlike cookies, session data is stored on the server-side, making it more secure.

Displaying All Session Variable Values

To start a session and display all session variable values:

php

<?php

// Start the session


85
session_start();

// Set some session variables for demonstration purposes

$_SESSION["username"] = "Sushma Kohli";

$_SESSION["email"] = "[email protected]";

$_SESSION["role"] = "admin";

IL
// Display all session variable values

echo "<h2>Session Variables:</h2>";

echo "<pre>";

print_r($_SESSION);

echo "</pre>";

?>
H
Summary

1. Cookies: Small pieces of data stored on the client-side. They can be used to maintain
SA
user preferences and sessions across multiple pages.

Creating a cookie named "user" that expires after 15 days:


php
setcookie("user", "Sushma Kohli", time() + (15 * 24 * 60 * 60), "/");

Retrieving the "user" cookie:


php
if (isset($_COOKIE['user'])) {

echo "User: " . $_COOKIE['user'];

2. Sessions: Used to store user information on the server-side across multiple pages
during their visit.

Displaying all session variable values:


php
session_start();
86
// Set some session variables

$_SESSION["username"] = "Sushma Kohli";

$_SESSION["email"] = "[email protected]";

$_SESSION["role"] = "admin";

// Display all session variables

echo "<h2>Session Variables:</h2>";

IL
echo "<pre>";

print_r($_SESSION);

○ echo "</pre>";


H
● Describe the PHP functions for the following :
I. Opening and Closing a FIle.
II. File reading and writing.

PHP Functions for File Handling


SA
PHP provides several functions for file handling, including opening, closing, reading, and
writing files. Here's a detailed explanation of these functions:

1. Opening and Closing a File

Opening a File

To open a file, use the fopen() function. This function requires two parameters: the file path
and the mode in which the file should be opened.

Syntax:

php

fopen(filename, mode);

Modes:

● 'r' - Read-only. Starts at the beginning of the file.


● 'r+' - Read/Write. Starts at the beginning of the file.
87
● 'w' - Write-only. Opens and truncates the file to zero length or creates a new file if it
doesn't exist.
● 'w+' - Read/Write. Opens and truncates the file to zero length or creates a new file if it
doesn't exist.
● 'a' - Write-only. Opens and writes to the end of the file or creates a new file if it doesn't
exist.
● 'a+' - Read/Write. Opens and writes to the end of the file or creates a new file if it
doesn't exist.
● 'x' - Write-only. Creates a new file and writes to it. Returns FALSE if the file already
exists.
● 'x+' - Read/Write. Creates a new file and writes to it. Returns FALSE if the file already
exists.

IL
Example:

php

<?php

$file = fopen("example.txt", "r"); // Open the file in read-only mode

if ($file) {
H
echo "File opened successfully.";

} else {
SA
echo "Failed to open the file.";

?>

Closing a File

To close an opened file, use the fclose() function.

Syntax:

php

fclose(file);

Example:

Php

<?php
88
$file = fopen("example.txt", "r");

// Perform file operations here

fclose($file); // Close the file

?>

2. File Reading and Writing

Reading a File

fread(): Reads a specified number of bytes from a file.


Syntax:

IL
php
fread(file, length);

Example:
php
<?php

$file = fopen("example.txt", "r");


H
$content = fread($file, filesize("example.txt")); // Read the entire
file

echo $content;
SA
fclose($file);

?>

fgets(): Reads a single line from a file.


Syntax:
php
Copy code
fgets(file, length);

Example:
php
<?php

$file = fopen("example.txt", "r");

while (($line = fgets($file)) !== false) {

echo $line;
89
}

fclose($file);

?>

file_get_contents(): Reads the entire file into a string.


Syntax:
php
Copy code
file_get_contents(filename);

Example:
php

IL
<?php

$content = file_get_contents("example.txt");

echo $content;

?>

Writing to a File
H
fwrite(): Writes a string to a file.
Syntax:
php
fwrite(file, string);
SA
Example:
php
<?php

$file = fopen("example.txt", "w");

fwrite($file, "Hello, World!");

fclose($file);

?>

file_put_contents(): Writes a string to a file (an easier way to write to a file compared to
fwrite()).
Syntax:
php
file_put_contents(filename, string);
90
Example:
php
<?php

file_put_contents("example.txt", "Hello, World!");

?>

Summary

● Opening a File: Use fopen() with appropriate mode ('r', 'w', etc.).
● Closing a File: Use fclose() to close an opened file.
● Reading a File: Use fread() to read a specific number of bytes, fgets() to read a

IL
single line, or file_get_contents() to read the entire file.
● Writing to a File: Use fwrite() to write to a file or file_put_contents() for an
easier method to write to a file.

H
SA

You might also like