Viva (oral exam) questions on PHP Error Handling

🎤 PHP Error Handling – Viva Questions

🟢 Basic Viva Questions

  1. What is error handling in PHP?
  2. Why is error handling important?
  3. Name different types of errors in PHP.
  4. What is a fatal error?
  5. What is a warning in PHP?
  6. What is a notice?
  7. What is a parse error?
  8. What is error_reporting()?
  9. How do you enable error display in PHP?
  10. How do you disable error display?

🟡 Conceptual Questions

  1. What is the difference between error and exception?
  2. What is exception handling?
  3. What are try, catch, and throw?
  4. Can we use multiple catch blocks?
  5. What is Throwable in PHP?
  6. What happens if an exception is not caught?
  7. What is the use of finally block?
  8. What is a custom error handler?
  9. What is set_error_handler()?
  10. What is trigger_error()?

🔵 Practical Viva Questions

  1. How will you handle division by zero error?
  2. How do you debug PHP code?
  3. What is var_dump() used for?
  4. Difference between echo and print_r() for debugging?
  5. How do you log errors in PHP?
  6. Where are PHP error logs stored?
  7. What is error_log()?
  8. How do you handle database connection errors?
  9. What happens when you use an undefined variable?
  10. How do you fix a white screen error?

🔴 Tricky / Advanced Viva Questions

  1. Can PHP handle fatal errors? How?
  2. What is register_shutdown_function()?
  3. Can we convert errors into exceptions?
  4. What is ErrorException?
  5. What is stack trace?
  6. What is the difference between die() and exit()?
  7. Can we continue execution after die()?
  8. What is the difference between include and require errors?
  9. What happens if you divide a number by zero in PHP 8?
  10. Why should errors not be shown in production?

🎯 Scenario-Based Viva

  1. Your website shows a blank page. What will you do?
  2. A user sees raw PHP error messages. Is it good? Why?
  3. API is failing. How will you debug it?
  4. Database connection failed. How will you handle it?
  5. You want to show a custom error page. How will you do it?

🧠 Quick Rapid-Fire (Teacher Favorite)

  • What is E_ALL?
  • What is E_WARNING?
  • What is E_NOTICE?
  • What is exception?
  • What is try-catch?
  • What is debugging?
  • What is logging?

🏆 Bonus Tip for Students

If stuck in viva, say:

“I will use try-catch for handling exceptions, enable error reporting during development, and log errors in production.”

important PHP Error Handling Interview Questions

🎯 PHP Error Handling – Interview Questions

🟢 Basic Level

1. What is error handling in PHP?

Answer:
Error handling is the process of detecting, managing, and responding to runtime or syntax errors in a PHP script.


2. What are the types of errors in PHP?

Answer:

  • Notice
  • Warning
  • Fatal Error
  • Parse Error
  • Deprecated Error

3. Difference between Warning and Fatal Error?

WarningFatal Error
Script continuesScript stops
Non-criticalCritical issue

4. What is error_reporting()?

Answer:
It defines which errors should be reported.

error_reporting(E_ALL);

5. How to display errors in PHP?

ini_set('display_errors', 1);
error_reporting(E_ALL);

🟡 Intermediate Level

6. What is Exception Handling?

Answer:
A mechanism to handle runtime errors using try, catch, and throw.


7. Explain try-catch block.

try {
// risky code
} catch (Exception $e) {
echo $e->getMessage();
}

8. What is the use of throw?

Answer:
It is used to generate an exception manually.


9. Difference between Error and Exception?

ErrorException
System-level issueApplication-level issue
Cannot always be handledCan be handled using try-catch

10. What is Throwable in PHP?

Answer:
Base interface for both Error and Exception (PHP 7+).


🔵 Advanced Level

11. What is a custom error handler?

Answer:
A user-defined function to handle errors using set_error_handler().

set_error_handler("myErrorFunction");

12. What is trigger_error()?

Answer:
Used to create a user-defined error.

trigger_error("Custom error", E_USER_WARNING);

13. How to log errors in PHP?

error_log("Error message", 3, "error.log");

14. What is the difference between die() and exception?

die()Exception
Stops script immediatelyCan be handled
No recoveryRecovery possible

15. How to handle database errors in PHP?

Answer:
Using try-catch with PDO or checking connection errors.


16. What is PDO exception mode?

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

17. What are best practices for error handling?

Answer:

  • Hide errors in production
  • Log errors instead
  • Use try-catch blocks
  • Validate inputs
  • Use custom handlers

🔥 Scenario-Based Questions

18. What will happen in this code?

echo 10/0;

Answer:
Division by zero → Warning or Error (PHP version dependent)


19. How will you handle API failure?

Answer:

  • Use try-catch
  • Check response status
  • Log errors
  • Show user-friendly message

20. How do you debug a white screen error?

Answer:

  • Enable error reporting
  • Check logs
  • Use var_dump()
  • Check syntax errors

🚀 Pro Interview Questions

21. Can we catch fatal errors in PHP?

Answer:
Not directly, but can use:

  • register_shutdown_function()

22. What is shutdown function?

register_shutdown_function(function() {
print_r(error_get_last());
});

23. How to convert errors into exceptions?

set_error_handler(function($errno, $errstr) {
throw new ErrorException($errstr, 0, $errno);
});

24. What is stack trace?

Answer:
A report of function calls leading to an error.


25. How to handle errors in production?

Answer:

  • Disable display_errors
  • Enable logging
  • Monitor logs
  • Use centralized error tracking

🎯 Bonus Tip (Interview Hack)

If interviewer asks:
👉 “How do you handle errors in real projects?”

Say:

“I use try-catch for critical operations, enable logging instead of displaying errors in production, use custom error handlers, and monitor logs for debugging.”

15. Error Handling (PHP)

Error handling in PHP helps you detect, manage, and debug issues in your code efficiently.


🔴 1. Error Types in PHP

PHP has different types of errors:

✅ Common Error Types:

Error TypeDescription
E_NOTICEMinor issues (e.g., undefined variable)
E_WARNINGNon-fatal errors (script continues)
E_ERRORFatal error (script stops)
E_PARSESyntax errors
E_DEPRECATEDUsing outdated features
E_ALLAll errors

📌 Example:

echo $name; // Undefined variable → Notice

🟡 2. Displaying Errors

Enable error reporting:

error_reporting(E_ALL);
ini_set('display_errors', 1);

Disable in production:

ini_set('display_errors', 0);

🟢 3. try-catch Blocks (Exception Handling)

Used to handle runtime errors (exceptions).

📌 Basic Example:

try {
$num = 10 / 0;
} catch (Throwable $e) {
echo "Error: " . $e->getMessage();
}

📌 Custom Exception:

function checkAge($age) {
if ($age < 18) {
throw new Exception("Underage!");
}
return "Access granted";
}try {
echo checkAge(16);
} catch (Exception $e) {
echo $e->getMessage();
}

🔵 4. Custom Error Handling

You can create your own error handler.

📌 Example:

function customError($errno, $errstr) {
echo "Error [$errno]: $errstr";
}set_error_handler("customError");// Trigger error
echo $test; // undefined variable

🟣 5. Trigger Custom Errors

trigger_error("Something went wrong!", E_USER_WARNING);

🟠 6. Debugging Techniques

✅ 1. Print Variables

print_r($data);
var_dump($data);

✅ 2. Use die() / exit()

die("Stop here");

✅ 3. Logging Errors

error_log("This is an error message", 3, "error.log");

✅ 4. Stack Trace

try {
throw new Exception("Test error");
} catch (Exception $e) {
echo $e->getTraceAsString();
}

🔥 7. Best Practices (Important)

  • ❌ Don’t show errors to users in production
  • ✅ Log errors instead
  • ✅ Use try-catch for critical operations
  • ✅ Validate inputs properly
  • ✅ Use custom error handlers for large apps

🚀 Real-World Example

try {
$conn = new mysqli("localhost", "root", "", "test"); if ($conn->connect_error) {
throw new Exception("Database connection failed");
} echo "Connected successfully";} catch (Exception $e) {
error_log($e->getMessage());
echo "Something went wrong. Please try later.";
}

Real-world API integration (payment, weather, AI)

🚀 1️⃣ Payment API Integration (Razorpay Example)

🔹 Use Case:

Accept online payments on your website.


🔹 Step 1: Install Razorpay SDK

composer require razorpay/razorpay

🔹 Step 2: Create Order (Backend PHP)

<?php
require 'vendor/autoload.php';use Razorpay\Api\Api;$api = new Api("YOUR_KEY_ID", "YOUR_SECRET");$order = $api->order->create([
'receipt' => 'order_rcptid_11',
'amount' => 50000, // amount in paise (₹500)
'currency' => 'INR'
]);echo json_encode($order);
?>

🔹 Step 3: Checkout Button (Frontend)

<script src="https://checkout.razorpay.com/v1/checkout.js"></script><button id="payBtn">Pay Now</button><script>
document.getElementById('payBtn').onclick = function () {
var options = {
key: "YOUR_KEY_ID",
amount: "50000",
currency: "INR",
name: "SOA Technology",
handler: function (response){
alert("Payment Successful: " + response.razorpay_payment_id);
}
};
var rzp = new Razorpay(options);
rzp.open();
}
</script>

🌦️ 2️⃣ Weather API Integration (OpenWeather)

🔹 Use Case:

Show live weather on website/app.


🔹 Step 1: API URL

https://api.openweathermap.org/data/2.5/weather?q=Delhi&appid=YOUR_API_KEY&units=metric

🔹 Step 2: PHP Integration

<?php
$city = "Delhi";
$apiKey = "YOUR_API_KEY";$url = "https://api.openweathermap.org/data/2.5/weather?q=$city&appid=$apiKey&units=metric";$response = file_get_contents($url);$data = json_decode($response, true);echo "City: " . $data['name'] . "<br>";
echo "Temperature: " . $data['main']['temp'] . "°C<br>";
echo "Weather: " . $data['weather'][0]['description'];
?>

🔹 Output Example:

City: Delhi
Temperature: 32°C
Weather: clear sky

🤖 3️⃣ AI API Integration (OpenAI Example)

🔹 Use Case:

Chatbot, content generator, AI tools (like your website)


🔹 Step 1: cURL Request

<?php
$apiKey = "YOUR_OPENAI_API_KEY";$data = [
"model" => "gpt-4.1-mini",
"messages" => [
["role" => "user", "content" => "Explain business ideas"]
]
];$ch = curl_init("https://api.openai.com/v1/chat/completions");curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Content-Type: application/json",
"Authorization: Bearer $apiKey"
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));$response = curl_exec($ch);
curl_close($ch);$result = json_decode($response, true);echo $result['choices'][0]['message']['content'];
?>

⚡ Real Project Ideas Using These APIs

💡 Combine APIs for powerful apps:

  • 🛒 E-commerce + Razorpay → Payment system
  • 🌍 Travel App + Weather API → Show destination weather
  • 🤖 AI Blog Generator → Auto content for SEO (perfect for your site)
  • 🧿 Spiritual AI Tool → AI + random logic (your current project 😉)

🔐 Important Best Practices

  • Never expose API keys in frontend
  • Use .env file for secrets
  • Add error handling:
if(!$response){
echo "API Error";
}
  • Validate user input (security)

🎯 What You Learn

  • Real-world backend skills
  • API request/response handling
  • JSON parsing
  • Building SaaS tools

14. Working with APIs (PHP)

1️⃣ REST API Basics

🔹 What is an API?

API (Application Programming Interface) allows two applications to communicate with each other.

Example:

  • Your website → sends request → API → returns data

🔹 What is REST API?

REST (Representational State Transfer) is a standard way to build APIs using HTTP methods.

🔹 Common HTTP Methods:

MethodUse
GETFetch data
POSTSend data
PUTUpdate data
DELETEDelete data

🔹 Example API Request:

GET https://api.example.com/users

🔹 Response (JSON):

{
"name": "Aditya",
"email": "test@gmail.com"
}

2️⃣ Fetch API Using PHP (cURL)

cURL is used in PHP to send API requests.


🔹 Simple GET Request:

<?php
$url = "https://jsonplaceholder.typicode.com/posts/1";$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);$response = curl_exec($ch);curl_close($ch);echo $response;
?>

🔹 POST Request Example:

<?php
$url = "https://jsonplaceholder.typicode.com/posts";$data = [
"title" => "My Post",
"body" => "This is content",
"userId" => 1
];$ch = curl_init($url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Content-Type: application/json"
]);$response = curl_exec($ch);curl_close($ch);echo $response;
?>

3️⃣ JSON Handling in PHP

JSON is the most common data format used in APIs.


🔹 Convert PHP Array → JSON

<?php
$data = [
"name" => "Aditya",
"age" => 25
];$json = json_encode($data);echo $json;
?>

🔹 Convert JSON → PHP Array

<?php
$json = '{"name":"Aditya","age":25}';$data = json_decode($json, true);echo $data['name'];
?>

🔹 Convert JSON → Object

<?php
$json = '{"name":"Aditya","age":25}';$data = json_decode($json);echo $data->name;
?>

4️⃣ Real-Life Example (API + JSON)

<?php
$url = "https://jsonplaceholder.typicode.com/users";$response = file_get_contents($url);$users = json_decode($response, true);foreach($users as $user){
echo $user['name'] . "<br>";
}
?>

5️⃣ Important Concepts for Students

  • API = Data source
  • JSON = Data format
  • cURL = Request tool
  • Always handle errors (important in real projects)

6️⃣ Bonus (Best Practice)

if(curl_errno($ch)){
echo "Error: " . curl_error($ch);
}

Give HR + technical mock interview

🎤 Mock Interview (PHP Developer – Security Focus)

🧑‍💼 HR Round

1. Tell me about yourself.

👉 (Expected: background, skills, projects, current work)


2. Why do you want to work with our company?

👉 Tip: Avoid generic answers like “growth” only.


3. What is your biggest strength?


4. What is your biggest weakness?


5. Describe a challenging project you worked on.


6. Where do you see yourself in 3–5 years?


7. Why should we hire you?


8. Have you ever faced a failure? What did you learn?



💻 Technical Round (PHP + Security)

🟢 Basic

9. What is the difference between GET and POST?


10. What is session and cookie?


11. How do you connect PHP to MySQL?


12. What is MVC architecture?



🟡 Intermediate (Important 🔥)

13. What is SQL Injection? How do you prevent it?

👉 Expect: Prepared Statements


14. What is XSS? Give example and prevention.


15. What is CSRF? How do you implement protection?


16. How does password_hash() work?


17. What is the difference between authentication and authorization?


18. How do you secure user login system?

👉 Expect:

  • Password hashing
  • Prepared statements
  • Session security


🔴 Advanced (High-Level)

19. How would you secure a file upload feature?


20. What steps will you take to secure a REST API?


21. What is session hijacking and prevention?


22. How do you prevent brute force attacks?


23. What security headers have you used?

👉 Example:

  • X-Frame-Options
  • CSP
  • X-XSS-Protection

24. What is rate limiting? Have you implemented it?



🧪 Practical Coding Question

25. Write secure login code (pseudo or real)

👉 Must include:

  • Prepared statements
  • password_verify()
  • Session handling


🧠 Bonus Rapid Fire

  • What is HTTPS?
  • What is hashing vs encryption?
  • What is JWT?
  • What is OWASP Top 10?

⭐ How to Use This

👉 Option 1:
Answer one by one, I’ll evaluate like interviewer

👉 Option 2:
Say “give answers” → I’ll provide perfect answers

👉 Option 3:
Say “take my interview” → I’ll do live interactive interview mode

PHP Security Interview Questions (Beginner → Advanced)

🔐 PHP Security Interview Questions

🟢 Beginner Level

1. What is SQL Injection?

👉 A vulnerability where attacker inserts malicious SQL into input fields to manipulate database.


2. How do you prevent SQL Injection in PHP?

👉 Using:

  • Prepared Statements (PDO / MySQLi)
  • Parameterized queries

3. What is XSS?

👉 Cross-Site Scripting allows attackers to inject JavaScript into web pages viewed by other users.


4. How to prevent XSS in PHP?

👉 Use:

htmlspecialchars($data, ENT_QUOTES, 'UTF-8');

5. What is CSRF?

👉 Cross-Site Request Forgery tricks users into performing unwanted actions.


6. How to prevent CSRF?

👉 Use CSRF tokens stored in session and validated on form submission.


7. What is password hashing?

👉 Converting password into secure hash so original password is not stored.


8. Which function is used for password hashing in PHP?

👉 password_hash()


9. How to verify password?

👉 password_verify()


10. What is data sanitization?

👉 Cleaning user input to remove unwanted or harmful data.


🟡 Intermediate Level

11. Difference between sanitization and validation?

👉

  • Validation → Check if data is correct
  • Sanitization → Clean the data

12. What is session hijacking?

👉 Attacker steals session ID to impersonate user.


13. How to prevent session hijacking?

👉

  • Use HTTPS
  • Regenerate session ID
  • Set secure cookies

14. What are secure cookies?

👉 Cookies with:

session_set_cookie_params([
'secure' => true,
'httponly' => true,
'samesite' => 'Strict'
]);

15. What is SameSite cookie attribute?

👉 Prevents CSRF by restricting cross-site cookie sending.


16. What is clickjacking?

👉 Attacker tricks user into clicking hidden elements.


17. How to prevent clickjacking?

header("X-Frame-Options: SAMEORIGIN");

18. What is Content Security Policy (CSP)?

👉 A security layer to prevent XSS by controlling resources.


19. What is file upload vulnerability?

👉 Uploading malicious files (like .php) to server.


20. How to secure file uploads?

👉

  • Validate file type
  • Rename file
  • Store outside public folder

🔴 Advanced Level

21. What is prepared statement internally?

👉 SQL query compiled first, then parameters safely bound → prevents injection.


22. What is output escaping vs input filtering?

👉

  • Input filtering → Clean data before saving
  • Output escaping → Secure display

23. What is the difference between htmlentities() and htmlspecialchars()?

👉

  • htmlspecialchars() → Converts basic characters
  • htmlentities() → Converts all HTML entities

24. What is timing attack in password comparison?

👉 Attacker measures response time to guess password.

👉 Prevent using:

hash_equals()

25. What is CORS and is it a security feature?

👉 Cross-Origin Resource Sharing
❗ Not a security feature, just controlled access mechanism


26. What is rate limiting?

👉 Limiting number of requests per user/IP to prevent abuse.


27. How to secure APIs in PHP?

👉

  • API keys / tokens
  • JWT authentication
  • Rate limiting
  • HTTPS

28. What is JWT?

👉 JSON Web Token used for secure authentication.


29. What are common PHP security best practices?

👉

  • Disable display_errors
  • Use HTTPS
  • Keep PHP updated
  • Validate all inputs
  • Use least privilege DB access

30. What is OWASP?

👉 Organization that lists top web security risks (OWASP Top 10)


💡 Pro Interview Tips

👉 Always mention:

  • Prepared Statements
  • CSRF Token
  • XSS Prevention
  • Password Hashing

👉 Real-world example = BIG PLUS ⭐

13. Security in PHP

Security is critical in web development. A single mistake can expose your database, users, and server.


🛑 1. SQL Injection Prevention

❌ Problem:

User input directly added to SQL query:

$username = $_GET['username'];
$query = "SELECT * FROM users WHERE username = '$username'";

👉 Attacker can input:

' OR 1=1 --

✅ Solution: Use Prepared Statements

Using PDO:

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);

Using MySQLi:

$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();

✔ Prevents SQL injection completely


⚠️ 2. XSS (Cross-Site Scripting) Protection

❌ Problem:

Displaying user input directly:

echo $_GET['name'];

👉 Attacker injects:

<script>alert('Hacked')</script>

✅ Solution: Escape Output

echo htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');

✔ Converts <script> → safe text
✔ Prevents JavaScript execution


🔁 3. CSRF Protection (Cross-Site Request Forgery)

❌ Problem:

User performs actions without verification


✅ Solution: Use CSRF Token

Step 1: Generate token

session_start();
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));

Step 2: Add in form

<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">

Step 3: Validate

if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die("Invalid CSRF token");
}

✔ Ensures request is from real user


🔑 4. Password Hashing

❌ Never do this:

$password = md5($password);

✅ Correct Method:

$hash = password_hash($password, PASSWORD_DEFAULT);

Verify password:

if (password_verify($password, $hash)) {
echo "Login successful";
}

✔ Uses strong encryption (bcrypt/argon)
✔ Automatically handles salting


🧼 5. Data Sanitization

Purpose:

Clean user input before processing


Methods:

Trim spaces:

$name = trim($_POST['name']);

Remove unwanted characters:

$name = filter_var($name, FILTER_SANITIZE_STRING);

Validate email:

$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

🚀 Bonus: Best Practices

✔ Always validate input (server-side)
✔ Use HTTPS
✔ Disable error display in production

ini_set('display_errors', 0);

✔ Use secure session:

session_regenerate_id(true);

✔ Set proper headers:

header("X-XSS-Protection: 1; mode=block");
header("X-Frame-Options: SAMEORIGIN");

📌 Summary Table

ThreatSolution
SQL InjectionPrepared Statements
XSShtmlspecialchars()
CSRFToken validation
Password Leakpassword_hash()
Dirty Inputfilter_var()

company-wise questions (TCS, Wipro, Infosys)

🟦 TCS (NQT / Technical Round)

👉 Focus: Basics + MCQs + simple coding

🔹 MCQs (Common Pattern)

  1. What is the default fetch mode in PDO?
  2. Difference between echo and print in PHP?
  3. Which is faster: mysqli or PDO? (Tricky ❗)
  4. What is the use of LIMIT in SQL?
  5. Which function prevents SQL injection?

🔹 Coding Questions

1. Insert data using PDO

$stmt = $conn->prepare("INSERT INTO users(name,email) VALUES(?,?)");
$stmt->execute([$name,$email]);

2. Fetch and display users

$stmt = $conn->query("SELECT * FROM users");
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);foreach($data as $row){
echo $row['name'];
}

🔹 Theory Questions

  • What is CRUD?
  • What is Primary Key?
  • What is SQL Injection?

👉 TCS Tip: Questions are easy but tricky wording.


🟪 Wipro (Technical + Coding Round)

👉 Focus: Logic + SQL + real use cases

🔹 SQL Questions

  1. Write query to find 2nd highest salary
SELECT MAX(salary) FROM employees 
WHERE salary < (SELECT MAX(salary) FROM employees);

  1. Difference between WHERE and HAVING
    👉 WHERE → before grouping
    👉 HAVING → after grouping

🔹 Coding Questions

1. Secure Login System (very common 🔥)

$stmt = $conn->prepare("SELECT * FROM users WHERE email=?");
$stmt->execute([$email]);
$user = $stmt->fetch();if($user && password_verify($pass,$user['password'])){
echo "Login success";
}

2. Update user data

$stmt = $conn->prepare("UPDATE users SET name=? WHERE id=?");
$stmt->execute([$name,$id]);

🔹 Scenario Questions

  • How will you secure user data?
  • How to handle large database?

👉 Wipro Tip: Focus on real-world usage + security


🟧 Infosys (Technical + HR Round)

👉 Focus: Concepts + scenario-based + clean coding

🔹 Theory Questions

  1. What is PDO and why preferred?
  2. What is normalization?
  3. Explain indexing
  4. What are transactions?

🔹 Coding Questions

1. Pagination (very important 🔥)

$limit = 10;
$offset = 0;$stmt = $conn->prepare("SELECT * FROM users LIMIT ? OFFSET ?");
$stmt->bindValue(1,$limit,PDO::PARAM_INT);
$stmt->bindValue(2,$offset,PDO::PARAM_INT);
$stmt->execute();

2. JOIN query

SELECT users.name, orders.id
FROM users
INNER JOIN orders ON users.id = orders.user_id;

🔹 HR + Scenario Questions

  • Explain a project you built
  • How do you debug errors?
  • What if database crashes?

👉 Infosys Tip: Explain logic clearly, not just code.


🔥 Common Questions Asked in ALL Companies

  • What is SQL Injection? How to prevent it?
  • Difference between bindParam() and bindValue()
  • What is password_hash()?
  • What is transaction?
  • What is index?

🎯 Smart Preparation Strategy

  • TCS → Practice MCQs + basics
  • Wipro → Practice SQL + real coding
  • Infosys → Focus on concepts + explanation

🚀 Final Interview Hack

If asked “How do you secure DB?” say:

“I use PDO prepared statements, input validation, password_hash, and transactions where needed to ensure security and consistency.”

placement-level MCQ test (PHP + MySQL PDO)

🧠 MCQ Test: PHP + MySQL (PDO)

🔹 Section A: Basics (1–10)

1. What does PDO stand for?
A) PHP Database Object
B) PHP Data Object
C) Personal Data Object
D) Program Data Object


2. Which function is used to connect PDO?
A) mysqli_connect()
B) new PDO()
C) connect_db()
D) db_open()


3. Which fetch mode returns associative array?
A) PDO::FETCH_NUM
B) PDO::FETCH_ASSOC
C) PDO::FETCH_OBJ
D) PDO::FETCH_BOTH


4. What does AUTO_INCREMENT do?
A) Deletes rows
B) Increases value automatically
C) Encrypts data
D) Joins tables


5. Which SQL command is used to read data?
A) INSERT
B) UPDATE
C) SELECT
D) DELETE


6. Which method executes prepared statement?
A) run()
B) execute()
C) query()
D) start()


7. Which is NOT a CRUD operation?
A) CREATE
B) READ
C) MODIFY
D) DELETE


8. Which is correct PDO DSN format?
A) mysql://localhost/db
B) mysql:host=localhost;dbname=test
C) localhost:mysql:test
D) db:mysql://localhost


9. Which function fetches single row?
A) fetch()
B) fetchAll()
C) get()
D) row()


10. Which function returns last inserted ID?
A) getLastId()
B) lastInsertId()
C) insertId()
D) lastId()


🔹 Section B: Intermediate (11–20)

11. Prepared statements help prevent?
A) Syntax error
B) SQL Injection
C) Server crash
D) Memory leak


12. Which symbol is used in named parameters?
A) ?
B) :
C) @
D) #


13. bindParam() binds by?
A) Value
B) Reference
C) Copy
D) Pointer


14. Which is safer?
A) Direct query
B) Prepared statement
C) Echo SQL
D) None


15. What does rowCount() return?
A) Columns
B) Tables
C) Affected rows
D) Errors


16. Which JOIN returns all rows from left table?
A) INNER JOIN
B) RIGHT JOIN
C) LEFT JOIN
D) FULL JOIN


17. Which is used for error handling?
A) try-catch
B) echo
C) die()
D) print()


18. Which function hashes password?
A) md5()
B) hash()
C) password_hash()
D) encrypt()


19. Which verifies password?
A) password_check()
B) password_verify()
C) verify_pass()
D) check_hash()


20. Index is used for?
A) Delete data
B) Speed up query
C) Insert data
D) Backup


🔹 Section C: Advanced (21–30)

21. Transaction starts with?
A) start()
B) beginTransaction()
C) open()
D) init()


22. Which method saves transaction?
A) save()
B) commit()
C) push()
D) execute()


23. Which undoes transaction?
A) cancel()
B) rollback()
C) undo()
D) reverse()


24. VARCHAR is?
A) Fixed length
B) Dynamic length
C) Integer
D) Boolean


25. CHAR is?
A) Dynamic
B) Fixed
C) Float
D) Object


26. ACID stands for?
A) Atomic, Consistent, Isolated, Durable
B) Active, Clear, Indexed, Data
C) Auto, Control, Input, Data
D) None


27. Which is faster for large data?
A) No index
B) Index
C) Random query
D) SELECT *


28. SQL Injection occurs when?
A) Query too fast
B) User input not sanitized
C) DB full
D) Server slow


29. LIMIT is used for?
A) Delete rows
B) Restrict results
C) Join tables
D) Insert rows


30. Which is best practice?
A) Plain SQL
B) Prepared statements
C) Hardcoded values
D) No validation


Answer Key

1-B   2-B   3-B   4-B   5-C
6-B 7-C 8-B 9-A 10-B11-B 12-B 13-B 14-B 15-C
16-C 17-A 18-C 19-B 20-B21-B 22-B 23-B 24-B 25-B
26-A 27-B 28-B 29-B 30-B

🎯 Score Evaluation

  • 25–30 → 🔥 Job Ready
  • 18–24 → 👍 Good, revise advanced
  • 10–17 → ⚠️ Needs practice
  • <10 → ❌ Learn basics again