🐘 PHP Beginner

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

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.