一、為何要優先使用PDO PHP手冊上說得很清楚: Prepared statements and stored procedures Many of the more mature databases support the concept of prepared statements. What are they They can be thought of as a kind of compiled template for the SQL that an application wants to run, that can be customized using variable parameters. Prepared statements offer two major benefits: The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize its plan for executing the query. For complex queries this process can take up enough time that it will noticeably slow down an application if there is a need to repeat the same query many times with different parameters. By using a prepared statement the application avoids repeating the analyze/compile/optimize cycle. This means that prepared statements use fewer resources and thus run faster. The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible).
即使用PDO的prepare方式,主要是提高相同SQL模板查詢性能、阻止SQL注入 同時,PHP手冊中給出了警告信息 Prior to PHP 5.3.6, this element was silently ignored. The same behaviour can be partly replicated with the PDO::MYSQL_ATTR_INIT_COMMAND driver option, as the following example shows. Warning The method in the below example can only be used with character sets that share the same lower 7 bit representation as ASCII, such as ISO-8859-1 and UTF-8. Users using character sets that have different representations (such as UTF-16 or Big5) must use the charset option provided in PHP 5.3.6 and later versions.
意思是說,在PHP 5.3.6及以前版本中,并不支持在DSN中的charset定義,而應該使用PDO::MYSQL_ATTR_INIT_COMMAND設置初始SQL, 即我們常用的 set names gbk指令。
我看到一些程序,還在嘗試使用addslashes達到防注入的目的,殊不知這樣其實問題更多, 詳情請看http://www.phpstudy.net/article/49205.htm 還有一些做法:在執行數據庫查詢前,將SQL中的select, union, ....之類的關鍵詞清理掉。這種做法顯然是非常錯誤的處理方式,如果提交的正文中確實包含 the students's union , 替換后將篡改本來的內容,濫殺無辜,不可取。
二、為何PDO能防SQL注入? 請先看以下PHP代碼: 復制代碼 代碼如下: php $pdo = new PDO("mysql:host=192.168.0.1;dbname=test;charset=utf8","root"); $st = $pdo- prepare("select * from info where id = and name =