When is quoting necessary in prepared statements of pdo in PHP?

爱⌒轻易说出口 提交于 2019-12-08 20:54:36

When using prepared statements you never have to escape/quote a string parameter for the dbms (parser) manually.
The comment relates to http://docs.php.net/pdo.prepared-statements:

Prepared statements are so useful that they are the only feature that PDO will emulate for drivers that don't support them.
I.e. if the driver doesn't support prepared statements PDO will still expose the prepare statements part of api and "translate" them to sql statements containing the parameters (e.g. INSERT INTO foo (x,y,z) values(1,2,3)). But it will do so transparently, i.e. it will automagically handle the quoting.

Prepared statements are prepared because you create markers for PDO to insert values, and these values can be named (for example, :accountId, :url) where PDO will find the named marker, or positional (specifically, a question mark (?)) where PDO will insert the values in the order the markers were placed.

eg:

$query = "SELECT user_id FROM users WHERE username = ?";
$statement = $pdo->prepare($query);
$statement->execute(array("John Smith"));

Notice the distinct lack of named parameters (specifically, using a ? instead of :username), and the positional style is used instead. It is purely a personal choice to use one or the other, although I find using named parameters is clearer when debugging.

Anyways. What this means is you do not have to quote if you are using prepared statements, and you do not have to worry about SQL injection when using prepared statements.

Now, what is really happening is PDO is asking the database driver (MySQL, PostgreSQL, MS SQL, Oracle, etc) to prepare the statement, but if the database driver cannot prepare it, PDO will simulate that feature. This where things start to get confusing, but you can safely forget it and just remember to use prepared statements with parameters.

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