Examples of parameterized queries [closed]

天涯浪子 提交于 2019-12-17 19:24:58

问题


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


回答1:


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"));



回答2:


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



来源:https://stackoverflow.com/questions/1894026/examples-of-parameterized-queries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!