Security/Guides/SQL Queries and 3rd Party Packages

SQL Queries
Connecting your application and database layers can pose security risks. Notably, SQL injection. Below is an outline of the do's and dont's of executing SQL queries in MediaWiki.

Never Correct
MediaWiki developers should never directly execute SQL queries through PHP's database extension functions (such as  or  ). Using the MediaWiki database wrappers helps ensure your queries end up at the correct database (which may or may not be the same as where the wiki itself is stored).

Why? Directly inserting a SQL string in one of these provided functions makes the developer responsible for escaping the SQL string themselves. Otherwise, applications are susceptible to SQL injection attacks.

Usually Correct
Most of the time, developers can use existing wrapper functions like  or   to perform SQL queries. When passing in parameters to these wrapper functions, it is important to use  on raw user data, as it correctly escapes the provided input (such as table name and  /  statements) to help prevent SQL injection.

Correct as of MW >1.35
As of MediaWiki 1.35, developers can use the SelectQueryBuilder class to create SQL  statements. This class allows function chaining so SQL queries are easily readable and don't require specifically formatted input parameters (like  does). The parameters to SelectQueryBuilder wrapper functions such as  should also be escaped via   before being passed in.

Rarely Correct
Rarely, you may need to execute a custom SQL query, one that does not fit within the parameters of the IDatabase wrapper functions or the  in which case you can use. This is useful for queries that are explicitly DBMS-dependent and are unsupported by the query wrappers such as.