0% found this document useful (0 votes)
9 views19 pages

Sample Questions

The document contains a series of PHP PDO programming questions and solutions, categorized into basic, moderate, and advanced levels. Each question involves creating tables, inserting records, updating, deleting, and displaying data using PDO. The solutions provide code snippets demonstrating how to implement these operations with error handling and best practices.
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)
9 views19 pages

Sample Questions

The document contains a series of PHP PDO programming questions and solutions, categorized into basic, moderate, and advanced levels. Each question involves creating tables, inserting records, updating, deleting, and displaying data using PDO. The solutions provide code snippets demonstrating how to implement these operations with error handling and best practices.
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

🟢 Basic Level PDO Questions

1️⃣ Question 1:
Create a table called students with columns:
student_id INT PRIMARY KEY , student_name VARCHAR(50) , and course
VARCHAR(30) .
Write a PHP program using PDO to insert a record with values (1, 'Rahul',
'BCA') and display a success message.

2️⃣ Question 2:
Create a table employees with columns:
emp_id INT PRIMARY KEY , emp_name VARCHAR(50) , and salary FLOAT .
Write a PHP script using PDO to insert a new employee with ID = 101,
name = "Amit", salary = 45000, and display “Employee added
successfully”.

3️⃣ Question 3:
Create a table books with columns:
book_id INT PRIMARY KEY , book_title VARCHAR(100) , and author
VARCHAR(50) .
Write a PHP program to insert a new record (10, 'Learn PHP', 'John Doe')
and display "Book record inserted".

4️⃣ Question 4:
Create a table departments with columns:
dept_no INT PRIMARY KEY , dept_name VARCHAR(40) .
Insert two departments ('HR', 'Finance') using PHP PDO and show
“Departments added successfully”.
5️⃣ Question 5:
Create a table customers with columns:
cust_id INT PRIMARY KEY , cust_name VARCHAR(50) , and city
VARCHAR(30) .
Write a PHP PDO program to insert a record with ID 5001, Name 'Sneha',
City 'Pune' and display “Record Inserted”.

🟡 Moderate Level PDO Questions


6️⃣ Question 6:
Create a table orders with columns:
order_id INT PRIMARY KEY , product_name VARCHAR(50) , and quantity
INT .
Write a PHP PDO script to insert 3 orders and then fetch & display all
order details.

7️⃣ Question 7:
Create a table students with columns:
roll_no INT PRIMARY KEY , name VARCHAR(50) , marks INT .
Write a PHP PDO program to update the marks of the student whose
roll_no = 101 to 95, then print “Marks updated successfully”.

8️⃣ Question 8:
Create a table movies with columns:
movie_id INT PRIMARY KEY , title VARCHAR(50) , and release_year
INT .
Write a PHP program to delete a movie record whose movie_id = 5 and
display “Movie deleted successfully”.

9️⃣ Question 9:
Create a table courses with columns:
course_id INT PRIMARY KEY , course_name VARCHAR(50) , and duration
INT .
Write a PHP PDO script to insert 3 courses and then display all the
records using a loop.

🔟 Question 10:
Create a table library_members with columns:
member_id INT PRIMARY KEY , member_name VARCHAR(50) , join_date
DATE .
Write a PHP program to:

Insert 3 members,
Fetch and display all member details in a tabular format.

🔵 Advanced / Combined CRUD Questions


1️⃣1️⃣ Question 11:
Create a table products with columns:
product_id INT PRIMARY KEY , product_name VARCHAR(50) , price
DECIMAL(8,2) .
Write a PHP program to:

Insert a product
Update its price
Display all products from the table.

1️⃣2️⃣ Question 12:


Create a table teachers with columns:
teacher_id INT PRIMARY KEY , teacher_name VARCHAR(50) , subject
VARCHAR(40) .
Write a PHP PDO script to:

Insert multiple teacher records using a loop


Retrieve all teachers who teach 'Math'
Display them in a formatted list.
1️⃣3️⃣ Question 13:
Create a table accounts with columns:
acc_no INT PRIMARY KEY , holder_name VARCHAR(50) , balance FLOAT .
Write a PHP program using PDO transactions to:

Insert two new accounts


If both inserts succeed → Commit the transaction
If any fails → Rollback.

1️⃣4️⃣ Question 14:


Create a table attendance with columns:
student_id INT PRIMARY KEY , student_name VARCHAR(50) , and
attendance_percent FLOAT .
Write a PHP PDO script to:

Insert records for 3 students


Display only those with attendance above 75%.

1️⃣5️⃣ Question 15:


Create a table exam_results with columns:
roll_no INT PRIMARY KEY , name VARCHAR(50) , marks INT .
Write a PHP program using PDO to:

Insert multiple students


Update one student’s marks
Delete one student
Display all remaining records.

🧠 Challenge / Viva-Type Questions


16️⃣ Question 16:
What is the purpose of using PDO::prepare() and PDO::execute() ?
Write a short PHP program demonstrating parameter binding using
:placeholders .

17️⃣ Question 17:


Write a PHP PDO script to create a database named college , and inside
it create a table faculty with id , name , designation , and salary .
Then insert one record and display “Database and table created
successfully with record inserted”.

18️⃣ Question 18:


Write a PHP program using PDO to:

Create a table patients with ( patient_id , patient_name ,


disease )
Insert 2 patients
Display them using fetchAll(PDO::FETCH_ASSOC) .

19️⃣ Question 19:


Write a PHP PDO script that connects to library_db , retrieves all
records from books table, and displays them in an HTML <table>
format.

20️⃣ Question 20:


Write a PHP program using PDO prepared statements to safely insert
user input (from an HTML form) into a users table having columns ( id ,
name , email ).

✅ Tip for Exams:


Your sir’s questions will typically check:
You can write the connection code properly ( try-catch ,
PDO::ATTR_ERRMODE ).
You can use prepared statements.
You can write CREATE TABLE, INSERT, SELECT, UPDATE, and
DELETE queries.
You can display output using echo or a loop.

SOLUTIONS

🟢 Basic Level PDO Question Solutions

Q1. students table – Insert record

<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=testdb",
"root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);

$pdo->exec("CREATE TABLE IF NOT EXISTS students (


student_id INT PRIMARY KEY,
student_name VARCHAR(50),
course VARCHAR(30)
)");

$stmt = $pdo->prepare("INSERT INTO students VALUES (?, ?,


?)");
$stmt->execute([1, 'Rahul', 'BCA']);
echo "Record inserted successfully!";
} catch (PDOException $e) {
echo $e->getMessage();
}
?>
Q2. employees table – Insert record

<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=testdb",
"root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);

$pdo->exec("CREATE TABLE IF NOT EXISTS employees (


emp_id INT PRIMARY KEY,
emp_name VARCHAR(50),
salary FLOAT
)");

$stmt = $pdo->prepare("INSERT INTO employees VALUES (?, ?,


?)");
$stmt->execute([101, 'Amit', 45000]);
echo "Employee added successfully!";
} catch (PDOException $e) {
echo $e->getMessage();
}
?>

Q3. books table – Insert record

<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=testdb",
"root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);

$pdo->exec("CREATE TABLE IF NOT EXISTS books (


book_id INT PRIMARY KEY,
book_title VARCHAR(100),
author VARCHAR(50)
)");

$stmt = $pdo->prepare("INSERT INTO books VALUES (?, ?,


?)");
$stmt->execute([10, 'Learn PHP', 'John Doe']);
echo "Book record inserted!";
} catch (PDOException $e) {
echo $e->getMessage();
}
?>

Q4. departments table – Insert multiple

<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=testdb",
"root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);

$pdo->exec("CREATE TABLE IF NOT EXISTS departments (


dept_no INT PRIMARY KEY AUTO_INCREMENT,
dept_name VARCHAR(40)
)");

$stmt = $pdo->prepare("INSERT INTO departments (dept_name)


VALUES (?)");
$stmt->execute(['HR']);
$stmt->execute(['Finance']);

echo "Departments added successfully!";


} catch (PDOException $e) {
echo $e->getMessage();
}
?>

Q5. customers table – Insert record


<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=testdb",
"root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);

$pdo->exec("CREATE TABLE IF NOT EXISTS customers (


cust_id INT PRIMARY KEY,
cust_name VARCHAR(50),
city VARCHAR(30)
)");

$stmt = $pdo->prepare("INSERT INTO customers VALUES (?, ?,


?)");
$stmt->execute([5001, 'Sneha', 'Pune']);

echo "Record Inserted!";


} catch (PDOException $e) {
echo $e->getMessage();
}
?>

🟡 Moderate Level PDO Question Solutions

Q6. orders table – Insert & display

<?php
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root",
"");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$pdo->exec("CREATE TABLE IF NOT EXISTS orders (


order_id INT PRIMARY KEY,
product_name VARCHAR(50),
quantity INT
)");
$stmt = $pdo->prepare("INSERT INTO orders VALUES (?, ?, ?)");
$stmt->execute([1, 'Keyboard', 5]);
$stmt->execute([2, 'Mouse', 10]);
$stmt->execute([3, 'Monitor', 2]);

echo "<h3>All Orders:</h3>";


foreach ($pdo->query("SELECT * FROM orders") as $row) {
echo "Order ID: {$row['order_id']} -
{$row['product_name']} ({$row['quantity']})<br>";
}
?>

Q7. students table – Update marks

<?php
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root",
"");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$pdo->exec("CREATE TABLE IF NOT EXISTS students (


roll_no INT PRIMARY KEY,
name VARCHAR(50),
marks INT
)");

$pdo->exec("INSERT IGNORE INTO students VALUES (101, 'Neha',


88)");

$stmt = $pdo->prepare("UPDATE students SET marks = :marks


WHERE roll_no = :roll_no");
$stmt->execute(['marks' => 95, 'roll_no' => 101]);

echo "Marks updated successfully!";


?>

Q8. movies table – Delete record


<?php
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root",
"");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$pdo->exec("CREATE TABLE IF NOT EXISTS movies (


movie_id INT PRIMARY KEY,
title VARCHAR(50),
release_year INT
)");

$pdo->exec("INSERT IGNORE INTO movies VALUES (5, 'Inception',


2010)");

$stmt = $pdo->prepare("DELETE FROM movies WHERE movie_id =


?");
$stmt->execute([5]);

echo "Movie deleted successfully!";


?>

Q9. courses table – Insert and display

<?php
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root",
"");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$pdo->exec("CREATE TABLE IF NOT EXISTS courses (


course_id INT PRIMARY KEY,
course_name VARCHAR(50),
duration INT
)");

$stmt = $pdo->prepare("INSERT INTO courses VALUES (?, ?, ?)");


$stmt->execute([1, 'PHP', 3]);
$stmt->execute([2, 'MySQL', 2]);
$stmt->execute([3, 'HTML', 1]);
echo "<h3>Courses List:</h3>";
foreach ($pdo->query("SELECT * FROM courses") as $row) {
echo "{$row['course_id']} - {$row['course_name']}
({$row['duration']} months)<br>";
}
?>

Q10. library_members table – Insert & Display

<?php
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root",
"");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$pdo->exec("CREATE TABLE IF NOT EXISTS library_members (


member_id INT PRIMARY KEY,
member_name VARCHAR(50),
join_date DATE
)");

$stmt = $pdo->prepare("INSERT INTO library_members VALUES (?,


?, ?)");
$stmt->execute([1001, 'Kavita', '2025-10-08']);
$stmt->execute([1002, 'Ravi', '2025-10-09']);
$stmt->execute([1003, 'Priya', '2025-10-10']);

echo "<h3>Library Members:</h3>";


foreach ($pdo->query("SELECT * FROM library_members") as $row)
{
echo "{$row['member_id']} - {$row['member_name']} -
{$row['join_date']}<br>";
}
?>

🔵 Advanced Level PDO Question Solutions


Q11. products table – Insert, update, display

<?php
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root",
"");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$pdo->exec("CREATE TABLE IF NOT EXISTS products (


product_id INT PRIMARY KEY,
product_name VARCHAR(50),
price DECIMAL(8,2)
)");

$stmt = $pdo->prepare("INSERT INTO products VALUES (?, ?,


?)");
$stmt->execute([1, 'Laptop', 55000]);

$pdo->prepare("UPDATE products SET price=? WHERE


product_id=?")->execute([60000, 1]);

echo "<h3>Product List:</h3>";


foreach ($pdo->query("SELECT * FROM products") as $row) {
echo "{$row['product_id']} - {$row['product_name']} - ₹
{$row['price']}<br>";
}
?>

Q12. teachers table – Insert and fetch

<?php
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root",
"");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$pdo->exec("CREATE TABLE IF NOT EXISTS teachers (


teacher_id INT PRIMARY KEY,
teacher_name VARCHAR(50),
subject VARCHAR(40)
)");

$stmt = $pdo->prepare("INSERT INTO teachers VALUES (?, ?,


?)");
$stmt->execute([1, 'Anita', 'Math']);
$stmt->execute([2, 'Rajesh', 'Science']);
$stmt->execute([3, 'Meena', 'Math']);

echo "<h3>Math Teachers:</h3>";


$stmt = $pdo->prepare("SELECT * FROM teachers WHERE subject =
?");
$stmt->execute(['Math']);
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
echo "{$row['teacher_name']} teaches {$row['subject']}
<br>";
}
?>

Q13. accounts table – Using Transactions

<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=testdb",
"root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);

$pdo->exec("CREATE TABLE IF NOT EXISTS accounts (


acc_no INT PRIMARY KEY,
holder_name VARCHAR(50),
balance FLOAT
)");

$pdo->beginTransaction();

$pdo->prepare("INSERT INTO accounts VALUES (?, ?, ?)")-


>execute([101, 'Rohan', 2000]);
$pdo->prepare("INSERT INTO accounts VALUES (?, ?, ?)")-
>execute([102, 'Suman', 5000]);

$pdo->commit();
echo "Transaction Successful!";
} catch (PDOException $e) {
$pdo->rollBack();
echo "Transaction Failed: " . $e->getMessage();
}
?>

Q14. attendance table – Filter output

<?php
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root",
"");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$pdo->exec("CREATE TABLE IF NOT EXISTS attendance (


student_id INT PRIMARY KEY,
student_name VARCHAR(50),
attendance_percent FLOAT
)");

$stmt = $pdo->prepare("INSERT INTO attendance VALUES (?, ?,


?)");
$stmt->execute([1, 'Anjali', 80]);
$stmt->execute([2, 'Karan', 70]);
$stmt->execute([3, 'Tina', 90]);

echo "<h3>Students with >75% Attendance:</h3>";


foreach ($pdo->query("SELECT * FROM attendance WHERE
attendance_percent > 75") as $row) {
echo "{$row['student_name']} -
{$row['attendance_percent']}%<br>";
}
?>
Q15. exam_results table – Full CRUD

<?php
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root",
"");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$pdo->exec("CREATE TABLE IF NOT EXISTS exam_results (


roll_no INT PRIMARY KEY,
name VARCHAR(50),
marks INT
)");

$stmt = $pdo->prepare("INSERT INTO exam_results VALUES (?, ?,


?)");
$stmt->execute([1, 'Ravi', 85]);
$stmt->execute([2, 'Simran', 90]);
$stmt->execute([3, 'Ajay', 75]);

$pdo->prepare("UPDATE exam_results SET marks=? WHERE


roll_no=?")->execute([95, 2]);
$pdo->prepare("DELETE FROM exam_results WHERE roll_no=?")-
>execute([3]);

echo "<h3>Remaining Students:</h3>";


foreach ($pdo->query("SELECT * FROM exam_results") as $row) {
echo "{$row['roll_no']} - {$row['name']} - {$row['marks']}
<br>";
}
?>

🧠 Viva / Conceptual Questions (16–20)


Each can be answered with small demonstration code (examples for
quick recall):

Q16. Purpose of prepare() & execute()


<?php
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root",
"");
$stmt = $pdo->prepare("INSERT INTO users (id, name, email)
VALUES (:id, :name, :email)");
$stmt->execute(['id'=>1, 'name'=>'Ravi',
'email'=>'[email protected]']);
echo "Record inserted using prepared statement!";
?>

Q17. Create DB + table + insert record

<?php
$pdo = new PDO("mysql:host=localhost", "root", "");
$pdo->exec("CREATE DATABASE IF NOT EXISTS college");
$pdo->exec("USE college");
$pdo->exec("CREATE TABLE IF NOT EXISTS faculty (
id INT PRIMARY KEY,
name VARCHAR(50),
designation VARCHAR(30),
salary FLOAT
)");
$pdo->prepare("INSERT INTO faculty VALUES (?, ?, ?, ?)")-
>execute([1, 'Asha', 'Lecturer', 45000]);
echo "Database, table, and record created successfully!";
?>

Q18. patients table – Insert & fetch

<?php
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root",
"");
$pdo->exec("CREATE TABLE IF NOT EXISTS patients (
patient_id INT PRIMARY KEY,
patient_name VARCHAR(50),
disease VARCHAR(50)
)");
$pdo->prepare("INSERT INTO patients VALUES (?, ?, ?)")-
>execute([1, 'Rita', 'Fever']);
$pdo->prepare("INSERT INTO patients VALUES (?, ?, ?)")-
>execute([2, 'Mohan', 'Cold']);

$stmt = $pdo->query("SELECT * FROM patients");


print_r($stmt->fetchAll(PDO::FETCH_ASSOC));
?>

Q19. Display records in HTML table

<?php
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root",
"");
echo "<table border='1'><tr><th>ID</th><th>Title</th>
<th>Author</th></tr>";
foreach ($pdo->query("SELECT * FROM books") as $row) {
echo "<tr><td>{$row['book_id']}</td><td>
{$row['book_title']}</td><td>{$row['author']}</td></tr>";
}
echo "</table>";
?>

Q20. Insert user input safely

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$pdo = new PDO("mysql:host=localhost;dbname=testdb",
"root", "");
$stmt = $pdo->prepare("INSERT INTO users (id, name, email)
VALUES (?, ?, ?)");
$stmt->execute([$_POST['id'], $_POST['name'],
$_POST['email']]);
echo "User added successfully!";
}
?>
<form method="POST">
ID: <input type="text" name="id"><br>
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>

Very important note

you may have to create the tables in phpmyadmin


MUST ADD after connecting to the database
$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);

You might also like