SQL injection

SQL injection

Description

Concatenating user input into an SQL string passed to APIs such as mysqli_query, query, or exec can allow SQL injection.

Potential impact

Attackers may bypass authentication, disclose data, or modify or delete records.

Remediation

Use PDO or mysqli prepared statements and pass values as bound parameters. Restrict dynamic table and column names to an allow-list.

Examples

Before

php
<?php
$id = $_REQUEST['id'];
$query = "SELECT * FROM users WHERE user_id = '$id'";
mysqli_query($db, $query);

After

php
<?php
$id = intval($_REQUEST['id']);
$stmt = $pdo->prepare('SELECT * FROM users WHERE user_id = :id');
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();

Explanation:

  • Before: Request input is inserted directly into the SQL statement.
  • After: The prepared statement treats the bound value as data.

References