4.7 Demonstrate ability to analyze and resolve security issues arising from site configuration or cu

Review SQL injection and more specifically examples of correct SQL injection syntax.

Examples from https://www.drupal.org/node/2489544. Use the database abstraction layer to avoid SQL injection attacks.

Use the database layer correctly. For example, never concatenate data directly into SQL queries.

Don't do this:

db_query('SELECT foo FROM {table} t WHERE t.name = '. $_GET['user']);

Instead, use proper argument substitution with db_query. The DB layer works on top of PHP PDO and uses an array of named placeholders:

Do This:

db_query("SELECT foo FROM {table} t WHERE t.name = :name", [':name' => $_GET['user']]);

For a variable number of argument, use an array of arguments or use db_select():

$users = ['joe', 'poe', $_GET['user']];
db_query("SELECT t.s FROM {table} t WHERE t.field IN (:users)",  [':users' => $users]);
$users = ['joe', 'poe', $_GET['user']];
$result = db_select('table', 't')
  ->fields('t', ['s'])
  ->condition('t.field', $users, 'IN')

db_query is deprecated and will be removed in Drupal 9 - instead you should use a database connection object and call the query method on it (the parameters are the same).

Another example of proper syntax.

$sql = "SELECT uid FROM users WHERE name = :name"; 
\Drupal::database->query($sql, [':name' => $_GET['name']]);

Other Resources

Last updated