Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
938 views
in Technique[技术] by (71.8m points)

mysql - PHP - Does PDO quote safe from SQL Injection?

$id  = trim((int)$_GET['id']);
$sql = 'SELECT * FROM users WHERE id = ' . $db->quote($id) . ' LIMIT 1';
$run = $db->query($sql)->fetch();

Does PDO's quote method is safe as prepared statements? Or i have to use prepared statements all the way in my script?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Basically quote() is safe as prepared statements but it depends on the proper implementation of quote() and of course also on it's consequent usage. Additionally the implementation of the used database system/PDO driver has to be taken into account in order to answer the question.

While a prepared statement can be a feature of the underlying database protocol (like MySQL) and will then being "prepared" on the database server (a server site prepare), it does not necessarily have to be and can be parsed on client site as well (a client site prepare).

In PDO this depends on:

  • Does the driver/database system support server side prepared statements?
  • PDO::ATTR_EMULATE_PREPARES must be set to false (default if the driver supports it)

If one of the conditions is not met, PDO falls back to client site prepares, using something like quote() under the hood again.


Conclusion:

Using prepared statements doesn't hurt, I would encourage you to use them. Even if you explicitly use PDO::ATTR_EMULATE_PREPARES or your driver does not support server site prepares at all, prepared statements will enforce a workflow where it is safe that quoting can't be forgotten. Please check also @YourCommonSense's answer. He elaborates on that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...