MYSQLi真正的转义函数显示新行和回车 [英] MYSQLi real escape function displaying new lines and carriage returns

查看:63
本文介绍了MYSQLi真正的转义函数显示新行和回车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本区域,当我尝试通过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() or htmlentities().

  • 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屋!

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