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 BY from user input

More most-asked PHP 8 questions

← All PHP 8 questions