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

PHP Unit-3,4

Uploaded by

Swastik Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

PHP Unit-3,4

Uploaded by

Swastik Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

PHP MySQL Exam Notes

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:

Understanding Files & Directories in PHP

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

Opening and Closing a File in PHP

PHP offers built-in functions to open and close files for various operations like reading, writing, or
appending.

Opening a File:

Use the `fopen()` function. It requires two parameters:


1. Filename (string): Path to the file.
2. Mode (string): The type of operation you intend to perform.

Common Modes:

Mode Description

`'r'` Open for reading.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/25
Mode Description

`'w'` Open for writing (clears file).

`'a'` Open for appending.


`'x'` Create a new file for writing.

Example:

php

$file = fopen("example.txt", "r"); // Open for reading


if ($file) {
echo "File opened successfully.";
} else {
echo "Failed to open file.";
}

Closing a File:

Use the `fclose()` function to close a file. It takes the file handle returned by `fopen()` as its
parameter.

Example:

php

fclose($file); // Close the file

Copying, Renaming, and Deleting a File

Copying a File:

Use the `copy()` function to copy a file.


Syntax:

php

copy(string $source, string $destination): bool

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:

Use the `rename()` function to rename or move a file.


Syntax:

php

rename(string $oldname, string $newname): bool

Example:

php

if (rename("oldname.txt", "newname.txt")) {
echo "File renamed successfully!";
} else {
echo "Failed to rename the file.";
}

Deleting a File:

Use the `unlink()` function to delete a file.


Syntax:

php

unlink(string $filename): bool

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:

Working with Directories in PHP

PHP provides several functions to interact with directories. These functions allow you to create, delete,
read, and manage directories.

Opening a Directory:

Use the `opendir()` function to open a directory. It returns a directory handle.


Syntax:

php

opendir(string $directory): resource|false

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

readdir(resource $dir_handle): string|false

Example:

php

while ($file = readdir($dir)) {


echo $file . "<br>";
}

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

closedir(resource $dir_handle): bool

Example:

php

closedir($dir);

Creating and Deleting Folders in PHP

Creating a Folder (Directory):

Use the `mkdir()` function to create a new directory.


Syntax:

php

mkdir(string $pathname, int $mode = 0777, bool $recursive = false, resource|null


$context = null): bool

Example:

php

if (mkdir("new_folder")) {
echo "Folder created successfully.";
} else {
echo "Failed to create folder.";
}

Deleting a Folder (Directory):

Use the `rmdir()` function to delete an empty directory.


Syntax:

php

rmdir(string $dirname): bool

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 in PHP

File uploading is a common feature in web applications. PHP provides a simple way to handle file
uploads via the `$_FILES` superglobal.

File Upload Form (HTML):

html

<form action="upload.php" method="post" enctype="multipart/form-data">


Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>

Handling File Upload (PHP):

The uploaded file details are stored in the `$_FILES` superglobal.


Syntax to move the uploaded file:

php

move_uploaded_file(string $from, string $to): bool

Example (upload.php):

php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

// Check if the file is an image


if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}

File Downloading in PHP

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.

File Download Script (PHP):

Use `readfile()` to read and output the file.


Set the `Content-Type` and `Content-Disposition` headers to prompt the download.

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

// Output the file content


readfile($file);
exit;
} else {
echo "File does not exist.";
}

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!

Introduction to Session Control, Session Functionality, What is a Cookie

Here are the notes on Session Control, Session Functionality, and Cookies in PHP:

Introduction to Session Control 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.

Session Functionality in PHP

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

Setting Session Variables:

Once the session is started, you can store data in the session using the `$_SESSION` superglobal
array.

php

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

Retrieving Session Variables:

You can access session variables to retrieve the stored data.

php

echo $_SESSION["username"]; // Outputs: JohnDoe

Modifying Session Variables:

You can modify the session variables just like regular variables.

php

$_SESSION["role"] = "guest"; // Modify the role

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

session_start(); // Always start the session first


session_unset(); // Remove all session variables
session_destroy(); // Destroy the session

Checking if a Session Variable is Set:

To check if a session variable is set, use `isset()`.

php

if (isset($_SESSION["username"])) {
echo "Username: " . $_SESSION["username"];
} else {
echo "No user logged in.";
}

What is a Cookie in PHP?

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

setcookie("user", "JohnDoe", time() + 3600, "/"); // Expires in 1 hour

Parameters of `setcookie`:

1. name: Name of the cookie.


2. value: Value to store in the cookie.
3. expire: Expiration time (in seconds since the Unix epoch).
4. path: Path where the cookie is available ("/" means it is available throughout the website).
5. domain: Domain for which the cookie is valid (optional).
6. secure: If true, the cookie will only be sent over secure HTTPS connections.

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

Checking if a Cookie is Set:

Use `isset()` to check if a cookie is set.

php

if (isset($_COOKIE["user"])) {
echo "Welcome " . $_COOKIE["user"];
} else {
echo "Cookie not set.";
}

Deleting a Cookie:

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

php

setcookie("user", "", time() - 3600, "/"); // Delete the cookie

Example of Cookie Usage:

php

// Set a cookie to remember the user’s name


setcookie("username", "JohnDoe", time() + 3600, "/");

// Retrieve the cookie


if (isset($_COOKIE["username"])) {
echo "Hello, " . $_COOKIE["username"];
} else {
echo "Cookie is not set.";
}

Differences Between Sessions and Cookies:

Aspect Session Cookie


Storage Server-side (in PHP) Client-side (in browser)

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:

Setting Cookies with PHP

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

`$name`: The name of the cookie.


`$value`: The value of the cookie.
`$expire`: The expiration time of the cookie (in seconds). You can use `time() + 3600` for a one-
hour expiration.
`$path`: The path where the cookie is available (e.g., `/` means the cookie is available throughout
the entire site).
`$domain`: The domain for which the cookie is valid (optional).
`$secure`: If `true`, the cookie will only be sent over secure (HTTPS) connections.
`$httponly`: If `true`, the cookie will not be accessible via JavaScript, enhancing security.

Example: Setting a Cookie

php

// Set a cookie that lasts for 1 hour


setcookie("user", "JohnDoe", time() + 3600, "/");

Accessing the Cookie:

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

Using Cookies with Sessions

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.

How Sessions and Cookies Work Together:

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.

Example: Using Cookies with Sessions

1. Start a Session:

php

session_start(); // Start the session to access session variables

2. Set a Session Variable:

php

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

3. Set a Cookie with the Session ID:

php

setcookie("session_id", session_id(), time() + 3600, "/");

4. Accessing Session and Cookie:

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

Syntax to Delete a Cookie:

php

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

`"cookie_name"`: The name of the cookie to delete.


`""`:Set the cookie’s value to an empty string.
`time() - 3600`: Set the expiration time to 1 hour ago to ensure the cookie is expired.

Example: Deleting a Cookie

php

setcookie("user", "", time() - 3600, "/"); // Delete the "user" cookie

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

Registering Session Variables in PHP

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.

Registering Session Variables:

1. Start the Session:

php

session_start(); // Always start the session before using session variables

2. Registering Session Variables:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 13/25
php

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

3. Accessing Session Variables:

php

echo "User: " . $_SESSION["username"];


echo "Role: " . $_SESSION["role"];

Example: Registering and Using Session Variables:

php

session_start();
$_SESSION["username"] = "JohnDoe"; // Register a session variable
echo "Hello, " . $_SESSION["username"]; // Retrieve and display session variable

Destroying Session Variables and the Session

If you want to remove session variables or destroy the entire session, you can use the following
functions.

Destroying Specific Session Variables:

1. Unset a Session Variable: Use `unset()` to remove a specific session variable.

php

unset($_SESSION["username"]); // Remove "username" session variable

2. Check if a Session Variable is Set:

php

if (isset($_SESSION["username"])) {
echo "Username is set.";
} else {
echo "Username is not set.";
}

Destroying the Entire Session:

1. Session Unset: `session_unset()` removes all session variables.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 14/25
php

session_start(); // Start the session


session_unset(); // Remove all session variables

2. Destroy the Session: `session_destroy()` completely destroys the session and removes the
session ID from the client.

php

session_destroy(); // Destroy the session

Example: Destroying the Session and Session Variables:

php

session_start(); // Start the session


unset($_SESSION["username"]); // Unset a specific session variable
session_destroy(); // Destroy the entire session

Summary of Key Functions:

Function Description
`setcookie()` Set a cookie with a name, value, expiration, etc.
`$_COOKIE[]` Access cookies sent by the client to the server.

`session_start()` Start a new session or resume the current session.


`$_SESSION[]` Store or retrieve session variables.
`session_unset()` Remove all session variables.
`session_destroy()` Destroy the current session and delete all session data.

`unset()` Remove a specific session variable.

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.

Using `mysqli` (Procedural Style)

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

Using `mysqli` (Object-Oriented Style)

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

Performing Basic Database Operations (DML)

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

INSERT INTO table_name (column1, column2, column3, ...)


VALUES (value1, value2, value3, ...);

PHP Example (Insert):

php

<?php
// Connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

$sql = "INSERT INTO users (username, email) VALUES ('JohnDoe', '[email protected]')";

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


echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

2. SELECT Operation

The `SELECT` statement is used to query the database and retrieve records from a table.

Syntax:

sql

SELECT column1, column2, ...


FROM table_name
WHERE condition;

PHP Example (Select):

php

<?php
// Connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

$sql = "SELECT id, username, email FROM users";


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

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

The `UPDATE` statement is used to modify existing records in a table.

Syntax:

sql

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

PHP Example (Update):

php

<?php
// Connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

$sql = "UPDATE users SET email = '[email protected]' WHERE username = 'JohnDoe'";

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


echo "Record updated successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

4. DELETE Operation

The `DELETE` statement is used to remove records from a table.

Syntax:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 18/25
sql

DELETE FROM table_name WHERE condition;

PHP Example (Delete):

php

<?php
// Connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

$sql = "DELETE FROM users WHERE username = 'JohnDoe'";

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


echo "Record deleted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

Summary of Basic SQL Operations:

Operation SQL Command Purpose

Insert `INSERT INTO` Adds new records to the table


Select `SELECT` Retrieves records from the table
Update `UPDATE` Modifies existing records in the table

Delete `DELETE FROM` Deletes records from the table

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:

Setting Query Parameters in PHP with MySQL

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.

Prepared Statement Syntax:

php

$stmt = $conn->prepare("SQL QUERY WITH PLACEHOLDERS"); // Prepare the query


$stmt->bind_param("data_types", $var1, $var2, ...); // Bind variables to placeholders
$stmt->execute(); // Execute the query

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

Example: Inserting Data with Query Parameters

php

<?php
// Connection to database
$conn = new mysqli($servername, $username, $password, $dbname);

// Prepare and bind


$stmt = $conn->prepare("INSERT INTO users (username, email) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $email); // "ss" means both are strings

// Set parameters and execute


$username = "JohnDoe";
$email = "[email protected]";
$stmt->execute();

echo "New record created successfully";

// Close statement and connection


$stmt->close();
$conn->close();
?>

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

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


echo "ID: " . $row["id"] . " - Username: " . $row["username"] . " - Email: " . $row["ema
il"];
}

$stmt->close();

2. INSERT Query:

php

$sql = "INSERT INTO users (username, email) VALUES (?, ?)";


$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $username, $email); // Bind string values
$stmt->execute();

3. UPDATE Query:

php

$sql = "UPDATE users SET email = ? WHERE username = ?";


$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $email, $username);
$stmt->execute();

4. DELETE Query:

php

$sql = "DELETE FROM users WHERE username = ?";


$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();

Types of SQL Joins

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

SELECT * FROM table1


CROSS JOIN table2;

Example:

sql

SELECT products.product_name, suppliers.supplier_name


FROM products
CROSS JOIN suppliers;

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

SELECT columns FROM table1


INNER JOIN table2 ON table1.column = table2.column;

Example:

sql

SELECT orders.order_id, customers.customer_name


FROM orders
INNER JOIN customers ON orders.customer_id = customers.customer_id;

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

Syntax for LEFT JOIN:

sql

SELECT columns FROM table1


LEFT JOIN table2 ON table1.column = table2.column;

Example (LEFT JOIN):

sql

SELECT employees.name, departments.department_name


FROM employees
LEFT JOIN departments ON employees.department_id = departments.department_id;

This query retrieves all employees, including those who do not belong to any department (where the
department info will be `NULL`).

Syntax for RIGHT JOIN:

sql

SELECT columns FROM table1


RIGHT JOIN table2 ON table1.column = table2.column;

Example (RIGHT JOIN):

sql

SELECT employees.name, departments.department_name


FROM employees
RIGHT JOIN departments ON employees.department_id = departments.department_id;

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

Example for FULL OUTER JOIN (Using UNION):

sql

SELECT employees.name, departments.department_name


FROM employees
LEFT JOIN departments ON employees.department_id = departments.department_id
UNION
SELECT employees.name, departments.department_name
FROM employees
RIGHT JOIN departments ON employees.department_id = departments.department_id;

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

SELECT a.column1, b.column2


FROM table_name a, table_name b
WHERE a.common_column = b.common_column;

Example:

sql

SELECT e1.employee_name AS Employee, e2.employee_name AS Manager


FROM employees e1
LEFT JOIN employees e2 ON e1.manager_id = e2.employee_id;

In this example, we are comparing each employee to their respective manager within the same
`employees` table.

Summary of SQL Joins:

Join Type Description Example Use Case


Useful when you need all combinations between
CROSS JOIN Returns Cartesian product of two tables.
tables.
Returns rows with matching values from
INNER JOIN Fetch related data from two tables.
both tables.
Returns all rows from the left table and Fetch all rows from the left table, even if no
LEFT JOIN
matched rows from the right. match in right.

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:

Prepared Statements help to securely insert parameters into queries.


Joins are essential for combining data from multiple tables based on a relationship.
Outer Joins (LEFT, RIGHT) include unmatched rows, while Inner Joins only return rows with
matches.

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

You might also like