PHP Unit-3,4
PHP Unit-3,4
I have my exam of Php Programming And Mysql subject. Give me notes on topics that I will give
you.
Sure! Let me know the topics, and I'll provide you with comprehensive notes.
Understanding file& directory, Opening and closing, a file, Coping, renaming and deleting a file
Here are the notes for the given topics in PHP Programming:
Files and directories are an integral part of web development. PHP provides various built-in functions to
interact with the file system.
Key Concepts:
File: A file is a collection of data stored on a disk.
Directory: A directory (or folder) is used to organize files.
PHP uses functions like `fopen()`, `fclose()`, `file_get_contents()`, etc., to work with files.
PHP can also interact with directories using functions like `opendir()`, `readdir()`, `mkdir()`,
and `rmdir()`.
PHP offers built-in functions to open and close files for various operations like reading, writing, or
appending.
Opening a File:
Common Modes:
Mode Description
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/25
Mode Description
Example:
php
Closing a File:
Use the `fclose()` function to close a file. It takes the file handle returned by `fopen()` as its
parameter.
Example:
php
Copying a File:
php
Example:
php
if (copy("source.txt", "destination.txt")) {
echo "File copied successfully!";
} else {
echo "Failed to copy the file.";
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/25
Renaming a File:
php
Example:
php
if (rename("oldname.txt", "newname.txt")) {
echo "File renamed successfully!";
} else {
echo "Failed to rename the file.";
}
Deleting a File:
php
Example:
php
if (unlink("example.txt")) {
echo "File deleted successfully!";
} else {
echo "Failed to delete the file.";
}
These notes summarize the essential concepts for understanding and managing files and directories in
PHP. Let me know if you'd like additional details or examples!
Working with directories, Creating and deleting folder, File Uploading & Downloading
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/25
Here are the notes for working with directories, creating and deleting folders, and file uploading &
downloading in PHP:
PHP provides several functions to interact with directories. These functions allow you to create, delete,
read, and manage directories.
Opening a Directory:
php
Example:
php
$dir = opendir("folder_name");
if ($dir) {
echo "Directory opened successfully.";
} else {
echo "Failed to open directory.";
}
Reading a Directory:
Use `readdir()` to read the contents of a directory. It returns the next entry in the directory.
Syntax:
php
Example:
php
Closing a Directory:
Use `closedir()` to close a directory handle after reading the directory contents.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 4/25
Syntax:
php
Example:
php
closedir($dir);
php
Example:
php
if (mkdir("new_folder")) {
echo "Folder created successfully.";
} else {
echo "Failed to create folder.";
}
php
Example:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 5/25
php
if (rmdir("folder_to_delete")) {
echo "Folder deleted successfully.";
} else {
echo "Failed to delete folder. Make sure it is empty.";
}
File uploading is a common feature in web applications. PHP provides a simple way to handle file
uploads via the `$_FILES` superglobal.
html
php
Example (upload.php):
php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 6/25
PHP allows you to offer files for download by setting appropriate headers and reading the file content.
Example (download.php):
php
$file = "path_to_file/file_to_download.txt";
if (file_exists($file)) {
// Set headers for download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Length: ' . filesize($file));
These notes cover the basics of working with directories, creating and deleting folders, and handling file
uploads and downloads in PHP. Let me know if you need further explanations or examples!
Here are the notes on Session Control, Session Functionality, and Cookies in PHP:
Session control is a mechanism in PHP to store and retrieve data about a user across multiple pages
during a single visit. Unlike cookies, which store data on the client's computer, sessions store data on
the server side, providing a more secure way of handling user information.
Key Concepts:
Session: A session is a way to store user information on the server for later use. Data is stored in a
session variable, and each user gets a unique session ID.
Session ID: The unique identifier used to track the user's session. It can be stored in a cookie or
URL.
PHP Session Variables: These are variables used to store user data during a session.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 7/25
PHP sessions are more secure than cookies because the data is not stored on the client side, and only a
session ID is passed between the client and the server.
PHP provides a simple and efficient way to manage sessions. The main functions related to sessions are:
Starting a Session:
To use sessions in PHP, you must first start the session at the beginning of each script.
php
session_start();
Once the session is started, you can store data in the session using the `$_SESSION` superglobal
array.
php
$_SESSION["username"] = "JohnDoe";
$_SESSION["role"] = "admin";
php
You can modify the session variables just like regular variables.
php
Destroying a Session:
If you want to destroy a session, you can use `session_destroy()`. This will delete all session
variables.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 8/25
php
php
if (isset($_SESSION["username"])) {
echo "Username: " . $_SESSION["username"];
} else {
echo "No user logged in.";
}
A cookie is a small piece of data stored on the client’s computer. It is sent by the server to the browser
and can be retrieved on subsequent requests. Cookies are used for storing user preferences, login
sessions, and tracking user activity across different pages and visits.
Key Concepts:
Cookie: A cookie is a small file that the server sends to the client's browser to store information.
Expiration Time: Cookies can be set to expire after a specific time or after the browser is closed.
Scope: Cookies are specific to a domain, meaning they are available to all pages within that
domain.
Setting a Cookie:
The `setcookie()` function is used to create a cookie in PHP. The function must be called before
any HTML output is sent to the browser.
php
Parameters of `setcookie`:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 9/25
7. httponly: If true, the cookie is only accessible via the HTTP protocol and not by JavaScript (for
security).
php
if (isset($_COOKIE["user"])) {
echo "Welcome " . $_COOKIE["user"];
} else {
echo "Cookie not set.";
}
Deleting a Cookie:
php
php
Security More secure (data stored on server) Less secure (data stored on client)
Expiry Data exists until session is destroyed Data persists until expiration time
Size Limit Can store large data Limited (around 4 KB per cookie)
Use Case User authentication, temporary data storage Remembering user preferences, tracking
These notes provide an overview of Session Control, Session Functionality, and Cookies in PHP. Let me
know if you'd like more examples or further clarification!
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 10/25
Setting Cookies with PHP. Using Cookies with Sessions, Deleting Cookies, Registering Session
variables, Destroying the variables and Session.
Here are the detailed notes on Setting Cookies with PHP, Using Cookies with Sessions, Deleting
Cookies, Registering Session Variables, and Destroying Session Variables and Session:
Cookies are set using the `setcookie()` function. This function must be called before any output is sent
to the browser (i.e., before any HTML or echo statements).
Syntax of `setcookie()`:
php
setcookie(string $name, string $value = "", int $expire = 0, string $path = "", string $doma
in = "", bool $secure = false, bool $httponly = false): bool
php
Once the cookie is set, it can be accessed using the `$_COOKIE` superglobal.
php
if (isset($_COOKIE["user"])) {
echo "Welcome " . $_COOKIE["user"];
} else {
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 11/25
echo "Cookie not set.";
}
Cookies and sessions are often used together to maintain persistent user information. While sessions
store data on the server, cookies can store session IDs or other information on the client side.
Session ID in Cookie: When you start a session with `session_start()`, PHP automatically sends a
session cookie to the client. This cookie contains the session ID, allowing the server to associate the
user with the correct session data on subsequent requests.
1. Start a Session:
php
php
$_SESSION["username"] = "JohnDoe";
php
php
if (isset($_COOKIE["session_id"])) {
echo "Session ID from cookie: " . $_COOKIE["session_id"];
}
if (isset($_SESSION["username"])) {
echo "Hello, " . $_SESSION["username"];
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 12/25
Deleting Cookies in PHP
To delete a cookie, you need to set its expiration time to a past date (before the current time).
php
php
After setting the cookie to expire, you can check if it’s been successfully deleted by verifying if it still
exists using `isset()`:
php
if (!isset($_COOKIE["user"])) {
echo "Cookie deleted.";
} else {
echo "Cookie still exists.";
}
Session variables are registered to store information that you want to maintain across multiple pages
during a user's session. These variables are stored on the server and are identified by the session ID.
php
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 13/25
php
$_SESSION["username"] = "JohnDoe";
$_SESSION["role"] = "admin";
php
php
session_start();
$_SESSION["username"] = "JohnDoe"; // Register a session variable
echo "Hello, " . $_SESSION["username"]; // Retrieve and display session variable
If you want to remove session variables or destroy the entire session, you can use the following
functions.
php
php
if (isset($_SESSION["username"])) {
echo "Username is set.";
} else {
echo "Username is not set.";
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 14/25
php
2. Destroy the Session: `session_destroy()` completely destroys the session and removes the
session ID from the client.
php
php
Function Description
`setcookie()` Set a cookie with a name, value, expiration, etc.
`$_COOKIE[]` Access cookies sent by the client to the server.
These notes cover the key concepts related to Setting Cookies with PHP, Using Cookies with Sessions,
Deleting Cookies, Registering Session Variables, and Destroying Session Variables and Sessions. Let
me know if you need further examples or clarification!
Connection with MySql Database, Performing basic database operation (DML) (Insert, Delete,
Update, Select)
Here are the notes on Connection with MySQL Database and Performing Basic Database Operations
(DML) in PHP:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 15/25
Connecting with MySQL Database in PHP
To interact with a MySQL database in PHP, you need to establish a connection using either the `mysqli`
extension or `PDO` (PHP Data Objects). The `mysqli` extension is widely used and supports both
procedural and object-oriented approaches.
php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "your_database_name";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "your_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";
?>
Data Manipulation Language (DML) refers to SQL commands used to manipulate data in a database. The
basic DML operations include INSERT, UPDATE, DELETE, and SELECT.
1. INSERT Operation
The `INSERT INTO` statement is used to insert new records into a table.
Syntax:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 16/25
sql
php
<?php
// Connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
2. SELECT Operation
The `SELECT` statement is used to query the database and retrieve records from a table.
Syntax:
sql
php
<?php
// Connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 17/25
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"] . " - Username: " . $row["username"] . " - Email: " . $row
["email"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
3. UPDATE Operation
Syntax:
sql
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
php
<?php
// Connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
4. DELETE Operation
Syntax:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 18/25
sql
php
<?php
// Connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
Important Notes:
Prepared Statements: For better security (to prevent SQL injection), always use prepared
statements when inserting data into the database, especially when accepting user input.
Error Handling: Always handle errors gracefully using `mysqli_error()` or `mysqli_errno()` to
avoid exposing database errors to the user.
Close Connection: Always close your database connection using `$conn->close()` to free up
resources.
These notes should provide a clear understanding of how to connect to a MySQL database and perform
basic database operations in PHP. Let me know if you'd like more details or examples!
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 19/25
Setting query parameter, Executing queryJoin (Cross joins, Inner joins, Outer Joins, Self joins.)
Here are the notes on Setting Query Parameters, Executing Queries, and Types of Joins (Cross Joins,
Inner Joins, Outer Joins, and Self Joins) in MySQL and PHP:
In PHP, query parameters are typically set using prepared statements to prevent SQL injection.
Prepared statements allow you to define SQL queries with placeholders and bind variables to these
placeholders.
php
`bind_param()`: The first argument specifies the data type of each parameter (`s` for string, `i` for
integer, `d` for double, `b` for blob).
`execute()`: Executes the prepared statement.
php
<?php
// Connection to database
$conn = new mysqli($servername, $username, $password, $dbname);
In this example, the `?` placeholders are replaced with `$username` and `$email` when the statement is
executed.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 20/25
Executing Queries in MySQL with PHP
1. SELECT Query:
To retrieve data from the database, you use the `SELECT` statement.
php
$sql = "SELECT id, username, email FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $username); // Bind the parameter as string
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
2. INSERT Query:
php
3. UPDATE Query:
php
4. DELETE Query:
php
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 21/25
A JOIN clause in SQL is used to combine rows from two or more tables based on a related column.
Here’s a breakdown of the common types of joins:
1. Cross Join
A CROSS JOIN returns the Cartesian product of the two tables, meaning it will return every possible
combination of rows between the two tables. If Table A has 3 rows and Table B has 2 rows, the result will
have 6 rows.
Syntax:
sql
Example:
sql
This query would return all possible combinations of products and suppliers.
2. Inner Join
An INNER JOIN returns only the rows where there is a match in both tables. If no match is found, the
row is excluded from the result.
Syntax:
sql
Example:
sql
This query retrieves the order IDs and customer names for orders that have matching customer records.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 22/25
3. Outer Join
An OUTER JOIN is used when you want to retrieve all rows from one table and the matching rows from
another table. If no match is found, `NULL` values are returned for columns from the table that does not
have a match.
There are three types of outer joins:
LEFT OUTER JOIN (LEFT JOIN): Returns all rows from the left table and matched rows from the
right table.
RIGHT OUTER JOIN (RIGHT JOIN): Returns all rows from the right table and matched rows from
the left table.
FULL OUTER JOIN: Returns all rows when there is a match in either left or right table. MySQL does
not directly support `FULL OUTER JOIN`, but you can achieve it using `UNION`.
sql
sql
This query retrieves all employees, including those who do not belong to any department (where the
department info will be `NULL`).
sql
sql
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 23/25
This query retrieves all departments, including those that have no employees assigned (where employee
names will be `NULL`).
sql
4. Self Join
A SELF JOIN is a join where a table is joined with itself. This is often used to compare rows within the
same table.
Syntax:
sql
Example:
sql
In this example, we are comparing each employee to their respective manager within the same
`employees` table.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 24/25
Join Type Description Example Use Case
Returns all rows from the right table and Fetch all rows from the right table, even if no
RIGHT JOIN
matched rows from the left. match in left.
FULL OUTER Returns rows with matching values in either Fetch all rows from both tables. (Achieved via
JOIN table. UNION in MySQL)
Compare rows within the same table (e.g.,
SELF JOIN Joins a table with itself.
employee-manager relationship).
Conclusion:
These concepts should help you with query execution and understanding different types of joins in SQL.
Let me know if you need further examples or explanations!
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 25/25