在 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模板网!