Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Examples of parameterized queries [closed]

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

like image 393
shin Avatar asked Dec 12 '09 17:12

shin


2 Answers

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"));
like image 108
Tor Valamo Avatar answered Nov 10 '22 02:11

Tor Valamo


PREPARE stmt_name FROM "SELECT name FROM Country WHERE code = ?";

SET @test_parm = "FIN";

EXECUTE stmt_name USING @test_parm;

Source: MySQL Dev: Prepared Statements

like image 4
Daniel Vassallo Avatar answered Nov 10 '22 03:11

Daniel Vassallo