我应该如何在MySQL数据库中存储换行符? [英] How should i store newlines in a MySQL database?

查看:596
本文介绍了我应该如何在MySQL数据库中存储换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



有点背景;我不知道如何在MySQL数据库中存储换行符。用户被要求完成一个textarea。它必须存储在MySQL数据库中,然后再读出,并将内容包含在HTML电子邮件中。



我应该将它们存储为:



1)字符串字面值 - 当然这是危险的和不正确的做法

<2>作为一个字符串 \r \\\
in - 当我从数据库中读取它时,它读取为4个字符,因此 nl2br()无法正确替换它们。 / p>
$ b 3)作为HTML < br /> - 因为必须将html实体编码为存储它最终被存储为< br /& gt; ,因此当它到达< br /> 被打印出来而不是实际的换行符。通过 html_entity_decode()传递它会解码其他需要编码的字符。



非常感谢任何帮助。

解决方案

按原样存储它,但首先转义。这是你的选择1.当你需要呈现这些数据时,应用你需要的任何函数来格式化它。如果您需要使用HTML显示,请使用 nl2br() htmlentities()函数。这也适用于邮件。



如果您有像这样的文本区域数据,

  $ text =您好,先生,
我是罗伯特');放桌学生; -
.....
您最听话的学生
.....;

只需将其保存起来,或者使用准备好的语句即可。

  $ text = $ mysqli-> real_escape_string($ text); 


I'm going around and around in circles in my mind trying to decide how best I should store newlines in a MySQL database.

A bit of background; the user is asked to complete a textarea. This has to stored in a MySQL database before being read back out and the content included in an HTML email.

Should I store them as:

1) String literal - surely this is dangerous and bad practice

2) As a string with \r\n in - when I read this back out of the database its read as 4 characters so nl2br() fails to correctly replace them.

3) As HTML <br /> - as it has to be html entity encoded to be stored it ends up being stored as &lt;br /&gt; so when it gets to the email <br /> is printed rather than an actual newline. Passing it through html_entity_decode() would decode other characters that need to be encoded.

Any help grately appreciated.

解决方案

Store it as it is but escape first. This is your option 1. When you need to present this data apply whatever function you need to format it. If you need to show it in HTML use nl2br() and htmlentities() functions. That'll work for mail also.

If you have a text area data like this,

$text="Hello Sir,
I am Robert'); Drop table students; --
.....
Yours most obedient pupil
.....";

Just store it as it is after you escape it, or use a prepared statement.

$text = $mysqli->real_escape_string($text);

这篇关于我应该如何在MySQL数据库中存储换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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