0% found this document useful (0 votes)
18 views11 pages

PHP UNIT 3 and 4

Uploaded by

Swastik Sharma
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)
18 views11 pages

PHP UNIT 3 and 4

Uploaded by

Swastik Sharma
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
You are on page 1/ 11

PHP UNIT 3 And 4

UNIT 3
Here are the detailed notes for Unit III as per your syllabus:

Working with Files and Directories

Understanding Files and Directories


1. File:
A file is a collection of data or information stored on a computer, typically
identified by a unique name and extension (e.g.,
example.txt ).

Files can store text, images, videos, or other data formats.

2. Directory:
A directory (or folder) is a container that holds files or other directories,
helping organize data in a hierarchical structure.

Opening and Closing a File


1. Opening a File:
Files must be opened to read, write, or modify data. Programming languages
use functions or commands for file operations.

Example in PHP:

$file = fopen("example.txt", "r"); // Opens the file in


read mode

Common file modes in PHP:

"r" : Read

"w" : Write (overwrites the file)

PHP UNIT 3 And 4 1


"a" : Append

2. Closing a File:
Closing a file releases the resources and ensures data integrity.

Example in PHP:

fclose($file);

Copying, Renaming, and Deleting a File


1. Copying a File:
Creates a duplicate of a file.

Example in PHP:

copy("source.txt", "destination.txt");

2. Renaming a File:
Changes the name of a file.

Example in PHP:

rename("oldname.txt", "newname.txt");

3. Deleting a File:
Removes a file from the directory.

Example in PHP:

unlink("filename.txt");

Working with Directories


1. Creating a Directory:

Example in PHP:

PHP UNIT 3 And 4 2


mkdir("new_folder");

2. Deleting a Directory:

Example in PHP:

rmdir("folder_name");

3. Listing Files in a Directory:

Example in PHP:

$files = scandir("folder_name");
foreach ($files as $file) {
echo $file . "<br>";
}

File Uploading and Downloading


1. File Uploading:
Uploading files to the server is a common web application feature.

Example process in PHP:

Use an HTML form with the enctype="multipart/form-data" attribute.

Handle the upload using the $_FILES array in PHP.

move_uploaded_file($_FILES["file"]["tmp_name"], "upload
s/" . $_FILES["file"]["name"]);

2. File Downloading:
Allows users to download files from the server.

Example in PHP:

header('Content-Disposition: attachment; filename="fil


e.txt"');

PHP UNIT 3 And 4 3


readfile("path/to/file.txt");

Session and Cookie

Introduction to Session Control


1. What is a Session?

A session is a way to store user information across multiple pages of a


web application.

Data is stored on the server and identified by a unique session ID.

2. Session Functionality:

Starting a Session:

session_start();

Setting Session Variables:

$_SESSION["username"] = "JohnDoe";

Accessing Session Variables:

echo $_SESSION["username"];

Destroying a Session:

session_destroy();

What is a Cookie?
A cookie is a small piece of data stored on the user's browser by the web
server. It is used for maintaining stateful information across browsing
sessions.

Example uses:

PHP UNIT 3 And 4 4


Remembering user preferences.

Storing login credentials.

Setting Cookies with PHP


1. Setting a Cookie:

setcookie("user", "JohnDoe", time() + (86400 * 30), "/");


// 1-day expiration

Parameters:

"user" : Name of the cookie.

"JohnDoe" : Value of the cookie.

time() + (86400 * 30) : Expiration time in seconds.

2. Accessing a Cookie:

echo $_COOKIE["user"];

3. Deleting a Cookie:

Set the expiration time to a past date.

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

These notes are detailed and suitable for both understanding and directly writing
in exams. Let me know if you'd like further clarification or move to the next topic!

UNIT 4
Here are detailed and easy-to-understand notes for Unit IV:

Introduction to RDBMS

PHP UNIT 3 And 4 5


What is RDBMS?
RDBMS (Relational Database Management System): A type of database
management system that organizes data into tables (relations) with rows and
columns.

Examples: MySQL, PostgreSQL, Oracle Database, SQL Server.

Key Features of RDBMS:

Structured Data Storage: Data is stored in tables.

Data Integrity: Maintains accuracy and consistency of data.

Relationships: Tables can be linked using primary and foreign keys.

SQL (Structured Query Language): Used to query and manipulate data.

Connecting with MySQL Database

Steps to Connect to a MySQL Database using PHP:


1. Establishing a Connection:

Example:

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_database";

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

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

PHP UNIT 3 And 4 6


2. PDO (PHP Data Objects):
A more secure and flexible way to connect.

Example:

try {
$conn = new PDO("mysql:host=localhost;dbname=my_dat
abase", "root", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE
_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}

Performing Basic Database Operations (DML)

1. INSERT Operation
Adds new rows to a table.

Example:

$sql = "INSERT INTO students (name, age) VALUES ('John Do


e', 20)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
}

2. DELETE Operation
Removes rows from a table.

Example:

$sql = "DELETE FROM students WHERE id=1";


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

PHP UNIT 3 And 4 7


echo "Record deleted successfully";
}

3. UPDATE Operation
Modifies existing rows.

Example:

$sql = "UPDATE students SET age=21 WHERE id=1";


if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
}

4. SELECT Operation
Retrieves data from a table.

Example:

$sql = "SELECT * FROM students";


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

if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Name: " . $row["nam
e"] . "<br>";
}
} else {
echo "0 results";
}

Setting Query Parameters

Using Prepared Statements:


Ensures security by preventing SQL injection attacks.

PHP UNIT 3 And 4 8


Example:

$stmt = $conn->prepare("SELECT * FROM students WHERE age =


?");
$stmt->bind_param("i", $age); // "i" stands for integer
$age = 20;
$stmt->execute();
$result = $stmt->get_result();

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


echo "Name: " . $row["name"] . "<br>";
}

Executing Queries

Executing a Query in PHP:


Use the query() or prepare() method.

Example:

$sql = "SELECT * FROM students";


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

Handling Errors:
Example:

if ($conn->error) {
echo "Error: " . $conn->error;
}

Joins in SQL

1. Cross Join

PHP UNIT 3 And 4 9


Combines all rows from two tables (Cartesian Product).

Example:

SELECT * FROM table1 CROSS JOIN table2;

2. Inner Join
Returns rows with matching values in both tables.

Example:

SELECT students.name, courses.course_name


FROM students
INNER JOIN courses ON students.course_id = courses.id;

3. Outer Joins
Left Outer Join: Returns all rows from the left table and matching rows from
the right table.

SELECT students.name, courses.course_name


FROM students
LEFT JOIN courses ON students.course_id = courses.id;

Right Outer Join: Returns all rows from the right table and matching rows from
the left table.

SELECT students.name, courses.course_name


FROM students
RIGHT JOIN courses ON students.course_id = courses.id;

4. Self Join
Joins a table with itself.

Example:

PHP UNIT 3 And 4 10


SELECT A.name AS Student1, B.name AS Student2
FROM students A, students B
WHERE A.course_id = B.course_id;

These notes provide a comprehensive explanation of the topics in Unit IV. Let me
know if you'd like further details or assistance with another unit!

PHP UNIT 3 And 4 11

You might also like