使用PDO准备参数化查询 [英] prepared parameterized query with PDO

查看:59
本文介绍了使用PDO准备参数化查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这种在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准备参数化查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆