Fail to unserialize the serialized data from mysql

Hello.

I have serialized an array and stored it into a mysql table.
(I don’t think this matters. The data type of the field is TEXT.)

After that, I read the data from the table, and unserialize.
However, it fails to restore to an array.

count(unserialize($data)) is 1
print_r(unserialize($data)) returns nothing

Could anyone suggest me where the problem is?

Thanks a lot!:slight_smile:

Base 64 Encode after serialization before inserting the serialized array. Than to restore base 64 decode and unserialize.

Oh, it works!
But why do I need to base64_encode it?
TEXT should be able to hold serialized data, isn’t it?

The output from serialize() should be treated as binary data. TEXT is a character data type, which implies a character set and encoding. So, somewhere between the time you send the string from php, until you get it back, if any conversion happens due to character sets, you get the wrong data back, and most likely serialize() will outright fail because string lengths were probably altered.

a binary data type would be better, like blob.

I have tried BLOB, but it does not work as well.
I wonder why base64_encode helps.

It helps because there is character conversion or stripping being performed, and base64 encoding uses a set of characters that tend to pass through unchanged in a lot encodings. Your query might not even be succeeding at all.