此PDO代码如何防止SQL注入? [英] How does this PDO Code protect from SQL Injections?

查看:187
本文介绍了此PDO代码如何防止SQL注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我一直在研究整个PDO,当我遇到此代码时,我正在阅读此博客教程,其解释是,如果我将PDO与数据绑定一起使用-用户将无法添加SQL注入.如何运作?

So I was looking into this whole PDO thing and I was reading this blog tutorial when I came across this code and the explanation being that if I use PDO with data binding - users won't be able to add SQL Injections. How does this work?


# no placeholders - ripe for SQL Injection!  
$STH = $DBH->("INSERT INTO folks (name, addr, city) values ($name, $addr, $city)");  

# unnamed placeholders  
$STH = $DBH->("INSERT INTO folks (name, addr, city) values (?, ?, ?); 

# named placeholders 
$STH = $DBH->("INSERT INTO folks (name, addr, city) value (:name, :addr, :city)");  

这是指向我的网站的链接,以防万一您想阅读以供参考. http://net.tutsplus.com/tutorials/php/为什么要使用phps-pdo-for-database-access/

Here's the link to the website I got it from incase you want to read it for reference. http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/

推荐答案

(第二行中有一个bug;该字符串未终止.在末尾添加");,您应该就可以了.当然,在获得任何结果之前,您还需要提供替换问号的值,然后实际运行查询.)

(There's a bug in the 2nd line; the string isn't terminated. Add a "); to the end, and you should be ok. It's on the page you linked to as well, so its their fault. You of course also need to supply the values that'll substitute the question marks, and then actually run the query, before you get any results.)

无论如何,要点. PDO查找?:name标记,并将它们(分别按顺序或按名称)替换为您指定的值.将值插入查询字符串后,将首先对它们进行处理,以转义可用于注入攻击的所有内容.

Anyway, to the point. PDO looks for the ? or :name markers, and replaces them (in order or by name, respectively) with the values you specify. When the values are inserted into the query string, they're first processed to escape anything that could be used for injection attacks.

这类似于在查询中使用值之前对值使用mysql_real_escape_string()(或更弱的addslashes()),但是PDO会自动执行并且效果更好.

It's similar to using mysql_real_escape_string() (or the weaker addslashes()) on a value before using it in a query, but PDO does it automatically and is better at it.

这篇关于此PDO代码如何防止SQL注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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