Executing SQL queries is security-sensitive. It has led in the past to the following vulnerabilities:

SQL injection is still one of the top 10 security vulnerabilities. Applications that execute SQL commands should neutralize any externally-provided values used in those commands. Failure to do so could allow an attacker to include input that changes the query so that unintended commands are executed, or sensitive data is exposed. Instead of trying to sanitize data by hand, SQL binding mechanisms should be used; they can be relied on to automatically perform a full sanitization.

This rule raises an issue when an execution of SQL queries might be susceptible to SQL injection. The goal is to guide security code reviews.

The following native database functions don't support prepared statements, thus their use is considered susceptible to injection.

In addition, the following function call will also raise an issue if the provided query is a string with one or more interpolated variable (containing "$" sign).

Ask Yourself Whether

You are at risk if you answered yes to this question.

Recommended Secure Coding Practices

You can also reduce the impact of an attack by using a database account with low privileges.

Questionable Code Example

$id = $_GET['id'];
mysql_connect('localhost', $username, $password) or die('Could not connect: ' . mysql_error());
mysql_select_db('myDatabase') or die('Could not select database');

$query = "SELECT * FROM myTable WHERE id = " + $id;
$result = mysql_query($query) or die('Query failed: ' . mysql_error());  // Questionable, seems to be susceptible to SQL injection

while ($row = mysql_fetch_object($result)) {
    echo $row->name;
}

Compliant Solution

$id = $_GET['id'];
try {
    $conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
    $stmt->execute(array('id' => $id));

    while($row = $stmt->fetch(PDO::FETCH_OBJ)) {
        echo $row->name;
    }
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

Exceptions

No issue will be raised if one of the functions is called with hard-coded string (no concatenation) and this string does not contain a "$" sign.

$result = mysql_query("SELECT * FROM myTable WHERE id = 42") or die('Query failed: ' . mysql_error());  // Compliant

See