php mysqli_real_escape_string,我应该使用它吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14011899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
mysqli_real_escape_string, should I use it?
提问by dontHaveName
I want to eliminate sql injection, should I use mysqli_real_escape_string()or is it clear in mysqli?
For example
我想消除sql注入,我应该使用mysqli_real_escape_string()还是在mysqli中清楚?例如
$nick = mysqli_real_escape_string($_POST['nick'])
回答by Mark Byers
You should use prepared statementsand pass string data as a parameter but you should not escape it.
您应该使用准备好的语句并将字符串数据作为参数传递,但不应对其进行转义。
This example is taken from the documentation:
此示例取自文档:
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
Note that the example does notcall mysqli_real_escape_string. You would only need to use mysqli_real_escape_stringif you were embedding the string directly in the query, but I would advise you to never do this. Always use parameters whenever possible.
注意,例子并没有打电话 mysqli_real_escape_string。mysqli_real_escape_string如果您直接在查询中嵌入字符串,则只需要使用,但我建议您永远不要这样做。尽可能始终使用参数。
Related
有关的
回答by Your Common Sense
Yes, you can use mysqli_real_escape_string to format strings, if you're going to implement your own query processor, using placeholders or some sort of query builder.
是的,您可以使用 mysqli_real_escape_string 来格式化字符串,如果您要实现自己的查询处理器,使用占位符或某种查询构建器。
If you're planning to use bare API functions in your code (which is obviously wrong practice but extremely popularized by local folks) - better go for the prepared statements.
如果您打算在代码中使用裸 API 函数(这显然是错误的做法,但在当地非常流行) - 最好使用准备好的语句。
Anyway, you can't "eliminate sql injection" using this function alone. mysql(i)_real_escape_stringfunctions do not prevent injections and shouldn't be used for whatever protection.
无论如何,你不能单独使用这个函数来“消除 sql 注入”。mysql(i)_real_escape_string函数不会阻止注入,也不应该用于任何保护。

