php 在 MySQL DB 中存储 base64 编码值的最佳方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18198780/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:08:02  来源:igfitidea点击:

Best way to store a base64 encoded value in MySQL DB?

phpmysqldatabasebase64

提问by Jamie Hutber

I have a value I'd like to store in my DB, does the Collation make any difference how a string like this

我有一个值我想存储在我的数据库中,排序规则对这样的字符串有什么影响吗

YToyOntzOjIwOiJUeXBlX29mX29yZ2FuaXNhdGlvbiI7czoyMDoiTWVtYmVyIG9mIFBhcmxpYW1lbnQiO3M6ODoiUG9zdGNvZGUiO3M6NzoiUEUxIDFKQSI7fQ==

Might be stored? Also, the only way I seem to be able to write these values to the DB is by using a BLOBthis seems to be a really rather wrong way of storing it.

可以储存吗?此外,我似乎能够将这些值写入数据库的唯一方法是使用BLOB这似乎是一种非常错误的存储方式。

回答by O. Jones

The collation only makes a difference if you need to ORDER BYor search the column. These base64 encoded items are probably not going to be searched or sorted.

排序规则仅在您需要ORDER BY或搜索列时才起作用。这些 base64 编码的项目可能不会被搜索或排序。

If your encoded items are guaranteed to be less than 64K bytes in length, define your column like this:

如果您的编码项目保证长度小于 64K 字节,请像这样定义您的列:

   `columnname` TEXT CHARACTER SET ascii,

This is exactly what's needed for a base64 encoded variable; the encoding process turns everything into displayable ASCII.

这正是 base64 编码变量所需要的;编码过程将所有内容转换为可显示的 ASCII。

If the items will be less than 16 megabytes in length, but some will be longer than 64k, use MEDIUMTEXTinstead of TEXT.

如果项目将长度小于16兆,但有些会比64K长,使用MEDIUMTEXT代替TEXT

Edityears later.

多年后编辑

The OQ encoded string, decoded, is a serialized php object:

解码后的 OQ 编码字符串是一个序列化的 php 对象:

a:2:{s:20:"Type_of_organisation";s:20:"Member of Parliament";s:8:"Postcode";s:7:"PE1 1JA";}

Observation 1: lots of this stuff gets stored in text columns without encoding it, using the utf8 or utf8mb4 character set. Lots? Yes. WordPress stores option data this way.

观察 1:使用 utf8 或 utf8mb4 字符集,很多这些东西被存储在文本列中而不对其进行编码。很多?是的。WordPress 以这种方式存储选项数据。

Observation 2: If it can be translated to JSON, you could use the JSON data type in recent versions of MySQL. JSON searches still aren't sargable, but they are structured.

观察 2:如果它可以转换为 JSON,您可以使用最新版本的 MySQL 中的 JSON 数据类型。JSON 搜索仍然不是 sargable,但它们是结构化的。