🐘 PHP Beginner

What is SQL injection and how do you prevent it in PHP?

Why Interviewers Ask This

Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for PHP development. It reveals whether you understand the building blocks that more complex concepts rely on.

Answer

SQL injection is an attack where an attacker manipulates a SQL query by injecting malicious SQL code through user input. Example: if you build a query like "SELECT * FROM users WHERE name = '" . $name . "'" and an attacker enters " OR '1'='1, they can bypass authentication. Prevention: always use prepared statements with PDO or MySQLi — they separate SQL code from data, making injection impossible. Additional measures: use a least-privilege database user, implement input validation, use an ORM (like Eloquent or Doctrine), and escape identifiers (table/column names) when they must be dynamic. Never concatenate user input directly into SQL strings.

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a PHP codebase.