Skip to content

Chapter 28 of 38

SQL Injection Prevention

Separate SQL and data, allowlist identifiers, restrict privileges, and review dynamic queries.

38 minutes 10 quick checksBy Subha Prasad
Lesson 28 of 38Course navigation

Lesson content

Read, practise, then check your understanding

SQL injection occurs when untrusted input changes command structure. Prepared statements bind values separately and are the primary defense.

Practical example

<?php
$stmt = $pdo->prepare('SELECT id, name FROM users WHERE email = :email');
$stmt->execute(['email' => $email]);
$allowedOrder = ['name' => 'name', 'created' => 'created_at'];
$order = $allowedOrder[$requestedOrder] ?? 'name';

Placeholders cannot safely bind table/column/direction identifiers; map those from trusted allowlists. Do not rely on manual quoting or HTML escaping. Restrict database privileges, avoid verbose production errors, and review every dynamic SQL fragment.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes SQL injection?
Which PHP term matches this description: Untrusted input changing SQL structure.
Which statement best describes parameterization?
Which PHP term matches this description: Binding data separately from the SQL command.
Which statement best describes identifier allowlist?
Which PHP term matches this description: Selection of table/order identifiers from trusted choices.
Which statement best describes least privilege?
Which PHP term matches this description: Giving the database account only required permissions.
Which statement best describes dynamic SQL?
Which PHP term matches this description: SQL structure assembled at runtime and requiring careful allowlisting.

0 of 10 checks passed

Your progress is saved on this device.

SQL Injection Prevention | PHP Lesson | Subha Prasad