Dynamically building SQL query strings can result in broken SQL syntax and open SQL injection attacks.
When SQL queries are constructed by concatenating or formatting user-supplied values directly into the query string, the structure of the query itself can be altered by a malicious input. This rule flags calls to SQL execution functions where the query string is built using string concatenation or format operators rather than parameterized queries or prepared statements. Unlike rule {rule:php:S3649}, this rule does not perform taint analysis — it flags all dynamically formatted SQL queries as a potential risk regardless of the data source.
If any part of a dynamically formatted query string originates from untrusted input, an attacker can manipulate the query to read, modify, or delete data they should not have access to, bypass authentication checks, or in some configurations execute operating system commands.
The following code builds a SQL query by concatenating a value directly into the query string.
$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');
$result = mysql_query("SELECT * FROM myTable WHERE id = " . $id); // Noncompliant, could be susceptible to SQL injection
while ($row = mysql_fetch_object($result)) {
echo $row->name;
}
$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();
}
No issue will be raised if one of the functions is called with a 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
The current implementation does not follow variables. It will only detect SQL queries which are concatenated or contain a $ sign
directly in the function call.
$query = "SELECT * FROM myTable WHERE id = " . $id; $result = mysql_query($query); // Not detected by this rule