Unsanitized external input in SQL query


Using unsanitized data, such as user input or request data, or externally influenced data passed to a function, in SQL query exposes your application to SQL injection attacks. This vulnerability arises when externally controlled data is directly included in SQL statements without proper sanitation, allowing attackers to manipulate queries and access or modify data.


  • Do not include raw external input in SQL queries. This practice can lead to SQL injection vulnerabilities.
    $sortingOrder = $_GET['untrusted'];
    $query = "SELECT id, name FROM products ORDER BY name LIMIT 20 $sortingOrder;"; // unsafe
  • Do validate all external input to ensure it meets the expected format before including it in SQL queries.
    $sortingOrder = $_GET['sortingOrder'] === 'DESC' ? 'DESC' : 'ASC';
  • Do use safe lists to validate external input, if dynamic input is required.
    private function validatedTableName($table_name)
    if in_array($table_name, $ALLOWED_TABLE_NAMES) {
    return $table_name
    // handle invalid table name
  • Do use prepared statements for database queries to separate SQL logic from external input, significantly reducing the risk of SQL injection.
    $stmt = $pdo->prepare("SELECT * FROM products WHERE id LIKE ? ORDER BY price {$sortingOrder}");
  • Do escape all external input using appropriate database-specific escaping functions before including it in SQL queries.
    $ok = mysqli_real_escape_string($conn, $_GET['ok']);


Associated CWE

OWASP Top 10


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