SQL Injection


SQL Injection Interview with follow-up questions

1. What is SQL Injection?

SQL Injection is a security vulnerability where an attacker manipulates a web application's SQL query by injecting malicious SQL code through user-supplied input. If the application concatenates user input directly into SQL strings without sanitization, the attacker can alter the query's logic.

Classic example of a vulnerable query:

// DANGEROUS — never do this
$username = $_POST['username']; // attacker supplies: admin' --
$query = "SELECT * FROM users WHERE username = '$username'";
// Resulting query: SELECT * FROM users WHERE username = 'admin' --'
// The -- comments out the rest, bypassing any password check

What an attacker can do:

  • Bypass authentication (logging in as any user without a password)
  • Extract data (UNION SELECT password FROM users)
  • Modify or delete data ('; DROP TABLE users; --)
  • Execute database server commands (on misconfigured servers)

Why it happens: SQL injection occurs when there is no separation between the query's code and its data. User input is interpreted as SQL syntax rather than as a literal string value.

Prevention — primary defense: prepared statements:

// SAFE — user input cannot alter the query structure
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = ?');
$stmt->execute([$_POST['username']]);

SQL injection consistently appears on the OWASP Top 10 list of web application security risks. Any interviewer covering PHP security will ask about it.

↑ Back to top

Follow-up 1

Can you explain how SQL Injection attacks are carried out?

SQL Injection attacks are carried out by exploiting vulnerabilities in a web application's input validation mechanisms. The attacker typically injects malicious SQL code into user input fields, such as login forms or search boxes. When the application fails to properly sanitize or validate the input, the injected SQL code is executed by the database server, leading to unauthorized actions or data leakage.

Follow-up 2

What are some examples of SQL Injection?

Here are some examples of SQL Injection attacks:

  1. Login Bypass: By injecting a specially crafted SQL code, an attacker can bypass the login mechanism and gain access to an application without a valid username and password.

  2. Information Disclosure: An attacker can manipulate a SQL query to retrieve sensitive information from a database, such as credit card numbers, passwords, or personal details.

  3. Database Modification: SQL Injection can be used to modify or delete data in a database, potentially causing data loss or unauthorized changes.

  4. Command Execution: In some cases, SQL Injection can be used to execute arbitrary commands on the database server, allowing the attacker to perform actions beyond the scope of the application.

Follow-up 3

Why is SQL Injection a serious security threat?

SQL Injection is a serious security threat because it can lead to unauthorized access, data leakage, and potential damage to the affected system. Here are some reasons why SQL Injection is considered a serious threat:

  1. Data Breaches: SQL Injection can allow attackers to retrieve sensitive information from databases, such as customer data, financial records, or intellectual property.

  2. Unauthorized Access: By bypassing authentication mechanisms, attackers can gain unauthorized access to an application or system, potentially compromising the confidentiality, integrity, and availability of the data.

  3. Application Compromise: SQL Injection can be used to modify or delete data in a database, alter application behavior, or even execute arbitrary commands on the underlying server, leading to complete compromise of the application.

  4. Reputation Damage: Successful SQL Injection attacks can result in significant reputation damage for organizations, leading to loss of customer trust and potential legal consequences.

2. How can SQL Injection be prevented in PHP?

SQL injection prevention in PHP has a clear hierarchy of defenses:

1. Prepared statements / parameterized queries — primary and sufficient defense

// PDO
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ? AND password_hash = ?');
$stmt->execute([$email, $hash]);

// MySQLi
$stmt = $mysqli->prepare('SELECT id FROM users WHERE email = ?');
$stmt->bind_param('s', $email);
$stmt->execute();

Prepared statements separate the query structure from the data. User input is never interpreted as SQL — it is always treated as a literal value.

2. Use a parameterized ORM or query builder Eloquent (Laravel), Doctrine, and similar tools parameterize queries automatically:

$user = User::where('email', $email)->first(); // safe

3. Validate and whitelist dynamic identifiers If table or column names must be dynamic (rare), validate against a strict allowlist:

$allowed = ['name', 'email', 'created_at'];
if (!in_array($column, $allowed, true)) {
    throw new InvalidArgumentException('Invalid column');
}
$stmt = $pdo->query("SELECT $column FROM users"); // safe because $column is whitelisted

4. Least-privilege database accounts Even if injection occurs, a DB user with only SELECT/INSERT/UPDATE/DELETE on specific tables limits the blast radius — the attacker cannot DROP tables or read system tables.

What NOT to use:

  • addslashes() — insufficient; bypassable in some encodings
  • mysql_real_escape_string() — removed in PHP 7; do not use
  • Blacklist filtering — fragile; attackers always find bypasses
↑ Back to top

Follow-up 1

What is the role of prepared statements in preventing SQL Injection?

Prepared statements play a crucial role in preventing SQL Injection attacks. When using prepared statements, the SQL query is precompiled and the query parameters are treated as data rather than as part of the SQL code. This means that the database engine knows in advance what parts of the query are data and what parts are SQL code. As a result, any attempt to inject malicious SQL code through user input will be treated as data and not executed as SQL code.

Here's an example of using prepared statements in PHP to prevent SQL Injection:

// Prepare the SQL statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');

// Bind the query parameters
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);

// Execute the prepared statement
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll();

Follow-up 2

Can you explain the concept of parameterized queries in relation to SQL Injection prevention?

Parameterized queries, also known as parameter binding or placeholders, are a way to pass data to an SQL query without directly including it in the query string. Instead of concatenating user input into the query string, parameterized queries use placeholders that are later replaced with the actual values. This ensures that user input is treated as data and not as part of the SQL code, effectively preventing SQL Injection attacks.

Here's an example of using parameterized queries in PHP to prevent SQL Injection:

// Prepare the SQL statement with placeholders
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = ? AND password = ?');

// Bind the query parameters
$stmt->bindParam(1, $username);
$stmt->bindParam(2, $password);

// Execute the prepared statement
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll();

Follow-up 3

How does input validation help in preventing SQL Injection?

Input validation is an important step in preventing SQL Injection attacks. By validating and sanitizing user input before using it in SQL queries, you can ensure that only valid and expected data is used. This helps to prevent attackers from injecting malicious SQL code.

Here are some best practices for input validation to prevent SQL Injection:

  1. Use whitelisting: Define a set of allowed characters or patterns for each input field and reject any input that does not match the whitelist.

  2. Use parameterized queries or prepared statements: As mentioned earlier, using parameterized queries or prepared statements ensures that user input is treated as data and not as part of the SQL code.

  3. Escape special characters: If you cannot use parameterized queries or prepared statements, make sure to escape special characters in user input before using it in SQL queries. This helps to neutralize any potential SQL Injection attacks.

  4. Validate input length and format: Check the length and format of user input to ensure that it meets the expected criteria. For example, if an input field expects a numeric value, validate that the input is indeed a number.

By combining input validation with other security measures like prepared statements, you can significantly reduce the risk of SQL Injection attacks.

3. What is the difference between SQL Injection and Blind SQL Injection?

Both are SQL injection attacks, but they differ in how the attacker receives information:

SQL Injection (Classic) The application returns database content directly in the HTTP response. The attacker can see query results, error messages, or data echoed back.

URL: /search?q=1' UNION SELECT username, password FROM users --
Response: The page displays usernames and password hashes

The attacker directly reads extracted data.

Blind SQL Injection The application is vulnerable but returns no data in the response — only a success/failure indication. The attacker must infer information indirectly.

Two subtypes:

Boolean-based blind: The attacker asks true/false questions and observes whether the page changes:

/user?id=1 AND SUBSTRING(username,1,1)='a'  → page shows normally (true)
/user?id=1 AND SUBSTRING(username,1,1)='b'  → page shows empty (false)

By iterating over characters, the attacker reconstructs data one bit at a time.

Time-based blind: When there is no visual difference, the attacker injects a time delay:

1; IF(SUBSTRING(username,1,1)='a', SLEEP(5), 0) --

If the response takes 5 seconds, the condition was true. Slower but works even when no content difference is visible.

Tools like SQLMap automate both techniques.

Prevention is the same for all types: prepared statements eliminate the injection vector entirely, making both classic and blind SQLi impossible.

↑ Back to top

Follow-up 1

Can you provide an example of a Blind SQL Injection attack?

Sure! Let's say we have a login form that takes a username and password. The application uses the following SQL query to authenticate the user:

SELECT * FROM users WHERE username = '' AND password = ''

In a Blind SQL Injection attack, the attacker can exploit a vulnerability in the username parameter to inject malicious SQL code. For example, the attacker can input the following username:

' OR 1=1; --

This will result in the following SQL query being executed:

SELECT * FROM users WHERE username = '' OR 1=1; --' AND password = ''

The injected code OR 1=1 always evaluates to true, bypassing the password check and allowing the attacker to log in without a valid password.

Follow-up 2

How can Blind SQL Injection be detected and prevented?

Blind SQL Injection can be more challenging to detect compared to regular SQL Injection because the attacker does not receive direct feedback. However, there are several techniques that can be used to detect and prevent Blind SQL Injection:

  1. Input validation and sanitization: Implement strict input validation and sanitization to prevent malicious SQL code from being injected in the first place.

  2. Parameterized queries: Use parameterized queries or prepared statements to separate the SQL code from the user input. This helps prevent SQL injection attacks, including Blind SQL Injection.

  3. Error handling: Monitor and log any unexpected errors or exceptions that occur during database queries. Unusual or repetitive errors may indicate a Blind SQL Injection attack.

  4. Web application firewalls (WAFs): Implement a WAF that can detect and block suspicious SQL injection attempts, including Blind SQL Injection.

  5. Regular security testing: Perform regular security testing, including penetration testing, to identify and fix any vulnerabilities in the application's code or configuration.

4. What are the consequences of a successful SQL Injection attack?

A successful SQL injection attack can have severe and wide-ranging consequences:

1. Data breach — unauthorized data access The attacker can use UNION SELECT statements or successive queries to extract the entire database contents — usernames, email addresses, password hashes, personal information, payment data, API keys, and any other stored data.

2. Authentication bypass Classic SQLi can manipulate WHERE clauses to log in as any user, including administrators, without knowing their password.

3. Data manipulation An attacker with write access can INSERT fraudulent records, UPDATE account balances or privileges, or DELETE data — causing financial loss, data corruption, or denial of service.

4. Schema and metadata discovery Via information_schema queries, attackers can enumerate all tables, columns, and stored procedures — providing a roadmap for further attacks.

5. Remote code execution (severe cases) On misconfigured MySQL/MariaDB with FILE privileges:

SELECT '' INTO OUTFILE '/var/www/shell.php'

This writes a PHP web shell to the server, giving the attacker full server control.

6. Privilege escalation If the database user has GRANT privileges, the attacker can create new admin accounts.

7. Compliance and legal consequences Data breaches trigger mandatory disclosure under GDPR (EU), CCPA (California), PCI-DSS (payment card data), and HIPAA (health data). Fines, class action lawsuits, and reputational damage follow.

↑ Back to top

Follow-up 1

How can an organization recover from a SQL Injection attack?

Recovering from a SQL Injection attack involves the following steps:

  1. Identify and mitigate the vulnerability: The organization should identify the root cause of the SQL Injection attack and fix the vulnerability that allowed the attack to occur. This may involve patching the application, updating libraries, or implementing secure coding practices.

  2. Assess the impact: The organization should assess the extent of the damage caused by the attack, including compromised data, unauthorized access, or data manipulation. This will help in determining the appropriate actions for recovery.

  3. Restore data integrity: If data has been modified or deleted, the organization should restore the affected data from backups or other reliable sources. Data integrity checks should be performed to ensure the accuracy and consistency of the restored data.

  4. Communicate with stakeholders: The organization should communicate the incident to relevant stakeholders, such as customers, partners, and regulatory authorities. Transparency and timely communication are crucial in maintaining trust and managing the aftermath of the attack.

  5. Strengthen security measures: After recovering from a SQL Injection attack, the organization should implement additional security measures to prevent future attacks. This may include regular security audits, penetration testing, code reviews, and employee training on secure coding practices.

Follow-up 2

What measures should be put in place to prevent future SQL Injection attacks?

To prevent future SQL Injection attacks, organizations should implement the following measures:

  1. Input validation and parameterized queries: Validate and sanitize all user input before using it in SQL queries. Use parameterized queries or prepared statements to separate SQL code from data, preventing SQL Injection attacks.

  2. Least privilege principle: Limit the privileges of database accounts and application users to only what is necessary for their intended functionality. Avoid using privileged accounts for routine operations.

  3. Regular security updates: Keep all software, including databases, web servers, and application frameworks, up to date with the latest security patches. Vulnerabilities in outdated software can be exploited by attackers.

  4. Web application firewalls (WAF): Implement a WAF to filter and block malicious SQL Injection attempts. WAFs can detect and block suspicious SQL queries before they reach the database.

  5. Secure coding practices: Train developers on secure coding practices, such as input validation, parameterized queries, and proper error handling. Regular code reviews and static code analysis can help identify and fix potential vulnerabilities.

  6. Database hardening: Configure the database server to follow security best practices, such as disabling unnecessary features, enabling encryption, and enforcing strong passwords for database accounts.

  7. Regular security audits: Conduct regular security audits and penetration testing to identify and address any vulnerabilities or weaknesses in the application and database infrastructure.

  8. Employee awareness and training: Educate employees about the risks of SQL Injection attacks and the importance of following secure coding practices. Regular training sessions can help raise awareness and prevent accidental introduction of vulnerabilities.

5. What are some tools that can be used to detect SQL Injection vulnerabilities?

Several categories of tools are used to detect SQL injection vulnerabilities:

Automated scanners:

SQLMap — the gold standard open-source SQL injection tool

sqlmap -u "https://example.com/user?id=1" --dbs --batch

Automatically detects and exploits SQLi vulnerabilities, fingerprints the database, and can dump tables. Used in both offensive security testing and authorized pen tests.

OWASP ZAP (Zed Attack Proxy) — free, open-source web application security scanner

  • Passive scanning (observes traffic for suspicious patterns)
  • Active scanning (sends crafted payloads to find SQLi, XSS, and other vulnerabilities)
  • Plugin ecosystem and CI/CD integration support

Burp Suite — the most widely used professional web security testing platform

  • Intercept and modify HTTP requests to manually test for SQLi
  • Scanner (Pro edition) automatically tests for injection points
  • Intruder and Repeater tools for manual fuzzing

Nikto — open-source web server scanner that checks for known vulnerabilities including SQLi-prone patterns

Static analysis tools (find SQLi in source code):

PHPStan with security extensions and Psalm can detect unsafe string concatenation in SQL queries.

SonarQube / Snyk Code — code quality and security platforms that detect injection vulnerabilities in PHP source code during development or CI/CD.

Manual testing: Always complement automated scanning with manual testing — tools miss logic-level vulnerabilities, second-order SQLi, and out-of-band injection channels. Use Burp Suite's Repeater to manually craft payloads for suspected injection points.

↑ Back to top

Follow-up 1

Can you explain how these tools work?

  1. SQLMap: SQLMap works by sending specially crafted SQL queries to the target application and analyzing the responses. It uses various techniques such as error-based, time-based, and boolean-based blind SQL Injection to identify vulnerabilities. It can also perform automated exploitation by retrieving data from the database or executing operating system commands.

  2. Acunetix: Acunetix works by scanning the target website and analyzing the HTTP requests and responses. It looks for patterns and behaviors that indicate potential SQL Injection vulnerabilities, such as unvalidated user input being used in SQL queries. It can also perform advanced techniques like parameter tampering and blind SQL Injection to detect vulnerabilities.

  3. Burp Suite: Burp Suite works by intercepting and modifying HTTP requests and responses between the client and the server. It allows you to manually test the application for SQL Injection vulnerabilities by modifying parameters and observing the behavior of the application. It also includes a scanner that can automatically detect SQL Injection vulnerabilities by analyzing the intercepted traffic.

  4. Nessus: Nessus works by scanning the target system or network for vulnerabilities. It uses various techniques to detect SQL Injection vulnerabilities, such as sending malicious input to web forms and analyzing the responses. It can also perform authenticated scans by logging in to the target application and testing for vulnerabilities.

Follow-up 2

What are the limitations of these tools?

While these tools are effective in detecting SQL Injection vulnerabilities, they have some limitations:

  1. False Positives: These tools may sometimes report false positives, i.e., they may identify a vulnerability that does not actually exist. This can happen due to various reasons, such as misconfiguration or unusual application behavior.

  2. False Negatives: These tools may also miss certain SQL Injection vulnerabilities, especially if the application uses advanced evasion techniques or if the vulnerabilities are not easily detectable.

  3. Limited Coverage: These tools may not be able to detect SQL Injection vulnerabilities in all types of applications or in all parts of the application. Some applications may have custom security measures or use non-standard techniques that are not covered by these tools.

  4. Manual Verification Required: It is always recommended to manually verify the reported vulnerabilities to ensure their accuracy. Automated tools can provide a good starting point, but manual testing is essential to thoroughly assess the security of an application.

Live mock interview

Mock interview: SQL Injection

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.