在PHP和MySql驱动的基于Web的应用程序中处理SQL的新的安全方法的新手,以保护代码免受SQL注入.我打算开始在PDO中使用mysqli.任何人都可以概述我应该如何开始和继续.
任何对任何文章的引用也会有所帮助.
提前致谢.
小智 11
创建连接
try {
$db = new PDO("mysql:dbname=".DB_NAME.";host=".DB_HOST,DB_USER,DB_PWD);
} catch (PDOException $e) {
die("Database Connection Failed: " . $e->getMessage());
}
Run Code Online (Sandbox Code Playgroud)
然后准备一份声明
$prep = $db->prepare("SELECT * FROM `users` WHERE userid = ':id'");
Run Code Online (Sandbox Code Playgroud)
如您所见,您可以通过在任何字符串前加上':'来标记您想要的每个参数.然后你要做的就是传递一个数组,将参数(:id)映射到执行时的值.
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
}
}
Run Code Online (Sandbox Code Playgroud)
使用"fetch"函数代替PDO :: FETCH_ASSOC,还有其他各种方法来获取数据.您可以使用fetchAll一次获取所有结果的数组,而不是逐行.或者您可以将信息数组作为0索引数组获取,或者甚至可以将结果直接提取到类实例中(如果字段名称与类的属性对齐).
PDO的所有文档都可以在这里找到:PHP.net PDO手册
| 归档时间: |
|
| 查看次数: |
6724 次 |
| 最近记录: |