PHP:使用准备好的语句进行注入保护
我熟悉使用 PHP 执行 mySQL 查询。但是,我一直在使用 reg exps 作为针对注入攻击的保护。在阅读了有关 SO 的几个问题/答案后,我决定选择准备好的陈述。
有两个可用选项(如果有更多选项,请告诉我):
问题 1
我试图理解链接页面上给出的代码示例。
对于 mysqli,示例 #1:
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
$stmt->bind_param("s", $city);
"s"
参数的作用是什么?
如果我需要超过 1 个参数,我该怎么做?
对于 PDO,示例 #1:
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
此处 PDO::ATTR_CURSOR
和 PDO::CURSOR_FWDONLY
的用途是什么?
问题 2
您会推荐 mysqli 或 PDO 中的哪一个?优点和缺点?
I am familiar with using PHP to perform mySQL queries. However, I have been using reg exps as protection against injection attacks. After reading several questions/answers here on SO, I've decided to opt for prepared statements instead.
There's two options available (let me know if there are more):
Question 1
I am trying to understand the code examples given on the linked pages.
For mysqli, Example #1 :
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
$stmt->bind_param("s", $city);
What does the "s"
parameter do?
If I need more than 1 paramater, how do I do that?
For PDO, Example #1 :
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
What is the purpose of PDO::ATTR_CURSOR
and PDO::CURSOR_FWDONLY
here?
Question 2
Which one, mysqli or PDO, would you recommend? Pros and cons?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
s
表示$city
应该是一个字符串PDO::ATTR_CURSOR
部分是您传递给 PDO 的设置的名称。值PDO::CURSOR_FWDONLY
(这是默认值,因此您无需指定 if)意味着每次调用PDOStatement::fetch()
您将获得结果集中的下一行。替代选项是 PDO::CURSOR_SCROLL - 但除非您明确知道需要此选项(并且您的数据库支持它),否则您应该将其保留为默认值。The
s
indicates that$city
is expected to be a stringThe
PDO::ATTR_CURSOR
part is the name of a setting you are passing to PDO. The valuePDO::CURSOR_FWDONLY
(which is the default, so you don't need to specify if) means that for each call you do toPDOStatement::fetch()
you will be given the next row in the result set. The alternative option would bePDO::CURSOR_SCROLL
- but unless you specifically know you need this (and your database supports it) you should leave it at the default.问题 1
s 参数将“:”绑定到 $city 具有的任何值。因此,如果您的 sql 是“
SELECT District FROM City WHERE Name = s
”,则执行的查询将为“SELECT District FROM CityWhere Name = $city
”。要绑定更多参数,只需为每个参数调用 bindParam 即可。您还可以将数组传递给 PDOStatement::execute。
问题 2
由于我使用一些不同的数据库(mysql 和 sqllite),我更喜欢使用 PDO。有关此主题的更多信息,请参阅 mysqli 或 PDO -有什么优点和缺点?。
Question 1
The s parameter binds ":" to whatever value $city has. So if your sql is "
SELECT District FROM City WHERE Name = s
", your executed query would be "SELECT District FROM City Where Name = $city
".To bind more parameters, just call bindParam for each parameter. You can also pass an array to PDOStatement::execute.
Question 2
Since i use some different databases (mysql and sqllite) i prefer working with PDO. Fore more information on this subject, please refer to mysqli or PDO - what are the pros and cons?.