php 在 MySQL 数据库中存储 &(Ampersand) 的最佳方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11704233/
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
The best way to store &(Ampersand) in MySQL database
提问by inrob
I'm building a category list and I'm unsure how to store the Ampersand symbol
in MySQL database. Is there any problem/disadvantage if I use '&'. Are there any differences
from using it in a html format '&'?
我正在构建一个类别列表,但不确定如何在 MySQL 数据库中存储 & 符号。如果我使用'&'. 与以 html 格式使用它有什么区别'&'吗?
采纳答案by Chris
Using '&' saves a few bytes. It is not a special characterfor MySQL. You can easily produce the &for output later with PHP's method htmlspecialchars(). When your field is meant to keep simple information, you should use plain text only, as this is in general more flexible since you can generate different kinds of markup etc. later. Exception: the markup is produced by a user whose layout decisions you want to save with the text (as in rich-text input). If you have tags etc. in your input, you may want to use &for consistency.
使用 '&' 可以节省几个字节。它不是MySQL的特殊字符。&稍后您可以使用 PHP 的方法轻松生成for 输出htmlspecialchars()。当您的字段旨在保留简单信息时,您应该只使用纯文本,因为这通常更灵活,因为您可以稍后生成不同类型的标记等。例外:标记是由用户生成的,您希望将其布局决定与文本一起保存(如在富文本输入中)。如果您的输入中有标签等,您可能需要使用&以保持一致性。
回答by Vatev
You should store it as &only if the field in the DB contains HTML (like <span class="bold">some text</span> & more). In which case you should be very careful about XSS.
您应该将其存储为 &仅当数据库中的字段包含 HTML(如<span class="bold">some text</span> & more)。在这种情况下,您应该非常小心XSS。
If the field contains some general data (like an username, title... etc) you should only escape it when you put it in your HTML (using htmlentitiesfor example).
如果该字段包含一些常规数据(如用户名、标题...等),则只有在将其放入 HTML 时才应将其转义(例如使用htmlentities)。
回答by Dave S
We store '&' into database fields all the time, it's fine to do so (at-least I've never heard an argument otherwise).
我们一直将 '&' 存储到数据库字段中,这样做很好(至少我从来没有听说过其他的争论)。
If you're only ever using the string in a HTML page you could just store the HTML safe &version I suppose. I would suggest that storing '&' and escaping it when you read it would be better though (in-case you need to use the string in a non-HTML context in the future).
如果您只在 HTML 页面中使用该字符串,您可以只存储&我认为的 HTML 安全版本。我建议存储 '&' 并在您阅读时将其转义会更好(以防将来您需要在非 HTML 上下文中使用该字符串)。
回答by ryno
Storing it as &is an appropriate method. You can echo it or use it in statements as &.
将其存储为&适当的方法。您可以回显它或在语句中使用它作为&.

