MYSQLi真正的转义函数显示新行和回车 [英] MYSQLi real escape function displaying new lines and carriage returns
问题描述
我有一个文本区域,当我尝试通过MYSQLi的real_escape函数和nl2br进行转义和清理时,仅输出会给我带来奇怪的结果.
我的php代码:
<?php
$db = new mysqli('localhost', 'user', 'pass', 'demo');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$postText = nl2br($db->escape_string($_POST['posting']));
?>
奇数的输出是:
i love this\r\n\r\nand this is gonna be funn.,
奇怪的是,当我只使用nl2br
而没有real_escape
时,它给出的输出很好,因为我不能信任用户的输入,因此显然无法前进.
请对此提供帮助.
仅在将要在SQL查询中使用输出时,才应应用SQL转义.
-
如果需要将值输出到页面上,请使用
htmlspecialchars()
或htmlentities()
. -
如果要在JavaScript文字中使用它,请使用
json_encode()
. -
等等.
此外,将nl2br()
写入数据库时不要使用它.而是在从数据库中获取它之后应用它.
i have a text area from which when i try to escape and sanitize through MYSQLi's real_escape function and nl2br and simply output is giving me odd results.
my php code:
<?php
$db = new mysqli('localhost', 'user', 'pass', 'demo');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$postText = nl2br($db->escape_string($_POST['posting']));
?>
the odd output is :
i love this\r\n\r\nand this is gonna be funn.,
and strangely when i just use nl2br
without real_escape
is giving the output fine which obviously can't move ahead with as i cant trust user"s input.
Please help on this..
You should only apply SQL escaping when the output is going to be used in a SQL query.
If you need to output the value onto a page, you use
htmlspecialchars()
orhtmlentities()
.If it's going to be used in a JavaScript literal, use
json_encode()
.Etc.
In short, each context has their own escaping; don't mix them up.
Also, don't use nl2br()
when you write it into the database; rather, apply it after you fetch it from the database.
这篇关于MYSQLi真正的转义函数显示新行和回车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!