Unsanitized user input in SQL query

Description

Including unsanitized data, such as user input or request data, in raw SQL queries makes your application vulnerable to SQL injection attacks.

Remediations

❌ Avoid raw queries, especially those that contain unsanitized user input

  $oops = $_GET['oops'];
$query = "SELECT id, name FROM products ORDER BY name LIMIT 20 $oops;";
$result = mysqli_query($conn, $query);

Instead, consider the following approaches when writing SQL queries

✅ Validate query input or use prepared statement wherever possible

  $sortingOrder = $_GET['sortingOrder'] === 'DESC' ? 'DESC' : 'ASC';
$productId = $_GET['productId'];
$stmt = $pdo->prepare("SELECT * FROM products WHERE id LIKE ? ORDER BY price {$sortingOrder}");
$stmt->execute(["%{$productId}%"]);

✅ Escape query input wherever possible

  $ok = mysqli_real_escape_string($conn, $_GET['ok']);
$query = "SELECT id, name FROM products ORDER BY name LIMIT 20 $ok;";
$result = pg_query($conn, $query);

Resources

Associated CWE

OWASP Top 10

Configuration

To skip this rule during a scan, use the following flag

bearer scan /path/to/your-project/ --skip-rule=php_lang_sql_injection

To run only this rule during a scan, use the following flag

bearer scan /path/to/your-project/ --only-rule=php_lang_sql_injection