Does calling query() on a container prevent SQL Injection? According to this link, db_query is now deprecated, and should be replaced by calling query() on a container containing a service injected with a database connection.

How do you prevent SQL Injection when using query()? The docs only cover how to do so when using db_query(), which is deprecated.

Thanks.
What reported there for db_query() is still valid for the method that you should use. In short, use placeholders when building the query, instead of concatenating the query string with unsafe input (e.g. the input obtained from from the user).

In Drupal 8 procedural code, you would use \Drupal::database()-&gt;query() instead of db_query(), but you would still avoid using code similar to the following one.

$count = \Drupal::database()-&gt;query('SELECT COUNT(DISTINCT foo) FROM {table} t WHERE t.name = '. $_GET['user'])-&gt;fetchField();


The correct code would be the following one.

$count = \Drupal::database()-&gt;query('SELECT COUNT(DISTINCT foo) FROM {table} t WHERE t.name = :name', [':name' =&gt; $_GET['user']])-&gt;fetchField();