← Back to Baseline

Why it Matters

Writing raw SQL queries with string concatenation is very dangerous. If user input is not filtered, attackers can inject SQL code into the query. This can lead to stolen data, deleted records, or even full control of the database.

Magento provides a safe database layer with prepared statements and bound parameters. Using these APIs ensures that input is properly handled, preventing SQL injection. Avoiding raw SQL keeps the application more secure and easier to maintain.

Verification Steps

Manual

# Search for dangerous SQL usage in custom modules
grep -R "SELECT " app/code/*
grep -R "INSERT " app/code/*
grep -R "UPDATE " app/code/*

# Look for code using string concatenation with variables in queries

Remediation / Fix Guidance

  1. Use Magento’s \Magento\Framework\DB\Adapter\AdapterInterface with bound parameters.
  2. Replace raw queries with select(), insert(), or update() methods from Magento’s DB layer.
  3. Never concatenate user input directly into SQL strings.
  4. Review custom extensions to ensure they follow the same standard.

Examples

Fail Example
// Unsafe raw SQL
$connection->query("SELECT * FROM customers WHERE id = " . $_GET['id']);
Pass Example
// Safe prepared query
$select = $connection->select()
    ->from('customers')
    ->where('id = ?', $customerId);
$result = $connection->fetchAll($select);

References