問題描述
$id = trim((int)$_GET['id']);
$sql = 'SELECT * FROM users WHERE id = ' . $db->quote($id) . ' LIMIT 1';
$run = $db->query($sql)->fetch();
PDO 的引用方法作為準備好的語句是否安全?或者我必須在我的腳本中一直使用準備好的語句?
Does PDO's quote method is safe as prepared statements? Or i have to use prepared statements all the way in my script?
推薦答案
基本上 quote()
作為準備好的語句是安全的,但它取決于 quote()
當然還有它的后續使用.此外,必須考慮使用的數據庫系統/PDO 驅動程序的實現才能回答問題.
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.
雖然準備好的語句可以是底層數據庫協議(如 MySQL)的一個特性,然后將在數據庫服務器上準備好"(服務器站點準備),它不一定必須并且也可以在客戶端站點上解析(客戶端站點準備).
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).
在 PDO 中,這取決于:
In PDO this depends on:
- 驅動程序/數據庫系統是否支持服務器端準備好的語句?
PDO::ATTR_EMULATE_PREPARES
必須設置為false
(如果驅動程序支持,則默認設置)
- Does the driver/database system support server side prepared statements?
PDO::ATTR_EMULATE_PREPARES
must be set tofalse
(default if the driver supports it)
如果其中一個條件不滿足,PDO 會回退到客戶端準備,再次在幕后使用類似 quote()
的東西.
If one of the conditions is not met, PDO falls back to client site prepares, using something like quote()
under the hood again.
結論:
使用準備好的語句沒有壞處,我鼓勵您使用它們.即使您明確使用 PDO::ATTR_EMULATE_PREPARES
或您的驅動程序根本不支持服務器站點準備,準備好的語句將強制執行一個工作流程,其中引用不會被忘記.另請檢查@YourCommonSense 的回答.他詳細說明了這一點.
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.
這篇關于PHP - PDO 引用是否安全從 SQL 注入?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!