What are prepared statements in PHP?

A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency.

Prepared statements basically work like this:

  1. Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled “?” or :user). You can use text or a ‘?’symbol, both work.
  2. The database parses, compiles, and performs query optimisations on the SQL statement template, and stores the result without executing it.
  3. Execute: At a later time, the application binds the values to the parameters, and the database executes the statement. The application may execute the statement as many times as it wants with different values.

Compared to executing SQL statements directly, prepared statements have three main advantages:

  1. Prepared statements reduces parsing time as the preparation on the query is done only once (although the statement is executed multiple times).
  2. Bound parameters minimise bandwidth to the server as you need send only the parameters each time, and not the whole query.
  3. Prepared statements are very useful against SQL injections, because parameter values, which are transmitted later using a different protocol, need not be correctly escaped. If the original statement template is not derived from external input, SQL injection cannot occur.

Leave a Reply

Your email address will not be published.

XL Websites

XL Websites