shin shin - 3 months ago 20
MySQL Question

Examples of parameterized queries

Could anyone give me examples of how to use parameterized queries with MySQL/PHP please?

Answer

A parameterized query is essentially a query which abstracts away all the input. This has several good side effects, like making all input harmless (ie. no harmful injections are possible) and making it faster when used repeatedly, since it is pre-parsed and compiled, so the engine knows how to apply the input given. An example in pure mysql is:

PREPARE qry FROM "INSERT INTO tbl VALUES (?)";

The statement is now compiled and cached, and can be executed repeatedly without needing to recompile and interpret it:

SET @var = "some input";
EXECUTE qry USING @var;
SET @var = "some other input";
EXECUTE qry USING @var;

When used in PHP, it's usually like this (shortened):

$stmt = prepare('INSERT INTO tbl VALUES(?)');
execute($stmt, array("some input"));
execute($stmt, array("some other input"));
execute($stmt, array("some more input"));