PHP › Security
What is SQL injection, and how does using prepared statements with PDO help prevent this common vulnerability in PHP applications?
BeginnerAnswer
SQL injection happens when untrusted user input is inserted directly into a SQL query string, allowing an attacker to manipulate the query itself and potentially read, modify, or delete data they should never have access to, and prepared statements prevent this by sending the query structure and the user supplied values to the database separately, so the values are always treated as plain data and never as part of the executable query, no matter what characters they contain.
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);Real-world example A login form uses a prepared statement to check a submitted email address against the database, ensuring that even if an attacker types something like a quote followed by SQL commands into the email field, it is safely treated as a literal string rather than being executed as part of the query.