Consider the following SQL query built using string concatenation in an application:
sql = "SELECT * FROM users WHERE username = '" + user_input + "';"
If user_input is admin'; DROP TABLE users; --, what will be the result of executing this query?
SELECT * FROM users WHERE username = 'admin'; DROP TABLE users; --
Think about how the input breaks out of the string and adds a new command.
Because the input closes the string early and adds a DROP TABLE command, the database executes both the SELECT and the DROP commands, causing data loss.
Why is building SQL queries by concatenating strings with user input considered unsafe?
Focus on security risks related to user input.
Concatenating user input directly into SQL allows attackers to add harmful commands, leading to SQL injection vulnerabilities.
Which of the following SQL query constructions is vulnerable to SQL injection due to string concatenation?
Look for direct concatenation of variables into the query string.
Option A directly concatenates product_id into the query string, which can be manipulated by attackers. The other options use safe parameter binding.
A developer wrote this code to get user info:
query = "SELECT * FROM users WHERE email = '" + email + "'";
Users report that entering an email with a single quote causes errors. What is the main problem?
Think about how quotes inside strings affect SQL syntax.
When the email contains a single quote, it prematurely ends the string in the SQL query, causing syntax errors or injection risks.
Given the risk of SQL injection from string concatenation, which approach best prevents this vulnerability while querying a database?
Think about how to separate user data from SQL commands safely.
Parameterized queries ensure user input is treated as data only, preventing it from being executed as SQL code.