PHP 8 interview question · Most asked
How do you prevent SQL injection in PHP?
Summary
Use prepared statements with bound parameters (PDO or mysqli), never concatenate user input into SQL, and whitelist anything that can't be parameterized such as column names or sort direction.
Longer Answer
With PDO, set PDO::ATTR_EMULATE_PREPARES => false (for MySQL) so real server-side prepares are used, and PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION. Identifiers (table/column names, ORDER BY fields) can't be bound, so validate them against an allow-list. ORMs and query builders parameterize for you, but raw expressions (DB::raw, whereRaw) reintroduce risk.
Code Example
<?php
$pdo = new PDO($dsn, $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
]);
$sort = in_array($_GET['sort'] ?? '', ['name', 'created_at'], true) ? $_GET['sort'] : 'name';
$stmt = $pdo->prepare("SELECT id, name FROM users WHERE status = :status ORDER BY $sort");
$stmt->execute(['status' => $_GET['status'] ?? 'active']);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
Key Points
- Prepared statements for all values
- Allow-list identifiers and sort directions
- Exceptions error mode; disable emulated prepares where practical
- Least-privilege DB users
Explanation
Common mistakes
- Escaping with
addslashes()instead of parameterizing - Binding values but interpolating
ORDER BYfrom user input
More most-asked PHP 8 questions
- What are the most important features introduced in PHP 8.0?
- What happens to an HTTP request in a PHP-FPM application, and what does 'shared nothing' mean?
- How should passwords be stored in PHP?
- What are named arguments and what are their benefits and risks?
- What is constructor property promotion?
- How does `match` differ from `switch`?
- What are union types in PHP 8 and how do you use them?
- What are enums in PHP 8.1? Explain pure vs backed enums.