PHP:使用准备好的语句进行注入保护 [英] PHP: Injection protection using prepared statements
问题描述
我熟悉使用PHP执行mySQL查询.但是,我一直在使用reg exp来防御注入攻击.在阅读了关于SO的一些问题/答案之后,我决定选择准备好的语句.
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):
- mysqli prepared statements
- PDO prepared staments
问题1
我试图理解链接页面上给出的代码示例.
Question 1
I am trying to understand the code examples given on the linked pages.
对于 mysqli ,示例#1:
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
$stmt->bind_param("s", $city);
"s"
参数有什么作用?
如果我需要多个参数,该怎么办?
What does the "s"
parameter do?
If I need more than 1 paramater, how do I do that?
对于 PDO ,示例1:
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
PDO::ATTR_CURSOR
和PDO::CURSOR_FWDONLY
的目的是什么?
您会推荐使用哪个mysqli或PDO?优点和缺点?
Which one, mysqli or PDO, would you recommend? Pros and cons?
推荐答案
问题1
s参数将:"绑定到$ city的任何值.因此,如果您的sql是"SELECT District FROM City WHERE Name = s
",则您执行的查询将是"SELECT District FROM City Where Name = $city
".
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
".
要绑定更多参数,只需为每个参数调用 bindParam .您还可以将数组传递给PDOStatement :: execute.
To bind more parameters, just call bindParam for each parameter. You can also pass an array to PDOStatement::execute.
问题2
由于我使用一些不同的数据库(mysql和sqllite),因此我更喜欢使用PDO.有关此主题的更多信息,请参考 mysqli或PDO-优点和缺点是什么?.
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?.
这篇关于PHP:使用准备好的语句进行注入保护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!