What is parameterized query?

What is a parameterized query, and what would an example of such a query be in PHP and MySQL?


Solution 1:

A parameterized query (also known as a prepared statement) is a means of pre-compiling a SQL statement so that all you need to supply are the "parameters" (think "variables") that need to be inserted into the statement for it to be executed. It's commonly used as a means of preventing SQL injection attacks.

You can read more about these on PHP's PDO page (PDO being a database abstraction layer), although you can also make use of them if you're using the mysqli database interface (see the prepare documentation).

Solution 2:

This is a clear and succinct explanation of what it is, and how it works. How and Why to use Parameterization [archive link]

Essential the process involves the server preprocessing the request without parameters so it knows the type of query it is. So, for example a SELECT query is only a SELECT query, and cannot be concatenated by a parameter(request variable) to be a SELECT / DROP or some other MySql injection. Instead the injection data will be just string data in the parameter field.

Solution 3:

A parameterized query is a query in which placeholders are used for parameters and the parameter values are supplied at execution time.

Why use Parameterized Query

  1. The most important reason to use parameterized queries is to avoid SQL injection attacks.
  2. Secondly parameterized query takes care of scenario where sql query might fail for e.g. inserting of O'Baily in a field. Parameterized query handels such query without forcing you to replace single quotes with double single quotes.