如何在 MySQL 表中存储 php 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5054485/
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
How do I store an php object in a MySQL table?
提问by nkcmr
I have set up a table that has only one field for a BLOB (Binary large object) but when I try to Insert it into the table it throws an error stating that it failed to convert the object to a string. This is my Query:
我已经建立了一个只有一个字段用于 BLOB(二进制大对象)的表,但是当我尝试将它插入到表中时,它抛出一个错误,指出它未能将对象转换为字符串。这是我的查询:
mysql_query("INSERT INTO objects (inquery) VALUES($inquery)");
回答by ThiefMaster
Serializeit:
序列化它:
$str = serialize($object);
If your object contains private/protected fields it's also a good idea to base64_encode()
the serialized object as those properties will result in ascii-1 characters being used which would break when editing the column manually e.g. with phpMyAdmin..
如果您的对象包含私有/受保护字段,base64_encode()
那么序列化对象也是一个好主意,因为这些属性将导致使用 ascii-1 字符,这在手动编辑列时会中断,例如使用 phpMyAdmin ..
To restore your object, you simply unserialize()
the string (base64_decode()
it before if necessary).
要恢复您的对象,您只需unserialize()
使用字符串(base64_decode()
如有必要,请先使用它)。
回答by Mohamed Auf
use json_encode to encode the object before you save it in Mysql then json_decode to decode the object
在将对象保存在 Mysql 之前使用 json_encode 对对象进行编码,然后使用 json_decode 对对象进行解码