問題描述
在 PHP 和 MySql 驅動的基于 Web 的應用程序中處理 SQL 的這種新的安全方式的新方法,以保護代碼免受 SQL 注入.我打算開始在 PDO 中使用 mysqli.任何人都可以請概述我應該如何開始和繼續.
New to this new and secure way of handling SQL's in PHP and MySql driven web based application, to secure the code from SQL injections. I am planning to start using mysqli with PDO. Can anyone please outline how should i get started and proceed.
對任何文章的任何參考也會有所幫助.
Any reference to any article will also be helpful.
提前致謝.
推薦答案
創建連接
try {
$db = new PDO("mysql:dbname=".DB_NAME.";host=".DB_HOST,DB_USER,DB_PWD);
} catch (PDOException $e) {
die("Database Connection Failed: " . $e->getMessage());
}
然后準備一份聲明
$prep = $db->prepare("SELECT * FROM `users` WHERE userid = ':id'");
如您所見,您可以通過在任何字符串前加上 ':' 來標記您想要的每個參數.然后你要做的就是在執行時傳遞一個將參數 (:id) 映射到值的數組.
As you can see, you label each parameter you'd like by prefixing any string with ':'. Then all you do is pass an array mapping the parameter (:id) to the value when you execute.
if (!$prep->execute(array(":id" => $userinput))) {
$error = $prep->errorInfo();
echo "Error: {$error[2]}"; // element 2 has the string text of the error
} else {
while ($row = $prep->fetch(PDO::FETCH_ASSOC)) { // check the documentation for the other options here
// do stuff, $row is an associative array, the keys are the field names
}
}
除了具有獲取"功能的 PDO::FETCH_ASSOC 之外,還有多種其他方法可以獲取您的數據.您可以使用 fetchAll 一次獲取所有結果的數組,而不僅僅是逐行獲取.或者您可以將信息數組作為 0 索引數組獲取,或者您甚至可以將結果直接提取到類實例中(如果字段名稱與類的屬性對齊.)
Instead of PDO::FETCH_ASSOC with the "fetch" function, there are various other ways to get your data. You can use fetchAll to get an array of ALL the results at once instead of just going row by row. Or you can get the array of information as a 0-indexed array, or you can even fetch the results directly into a class instance (if the field names line up with the properties of the class.)
PDO 的所有文檔都可以在這里找到:PHP.net PDO 手冊
All the documentation of PDO can be found here: PHP.net PDO Manual
這篇關于使用 PDO 準備參數化查詢的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!