php/mysql : How to insert a gzcompress-ed string i

2019-03-30 13:33发布

问题:

I have been trying to compress and store a json encoded string into mysql, but I am getting "unexpected /" errors.

I also tried to use addslashes like this:

addslashes(gzcompress(json_encode($mystring)));

And to display

json_decode(gzuncompress(stripslashes($mystring)));

But it fails on insert with the error I mentioned.

I read somewhere a string with gzcompress should be stored as a blob, but I was hoping there is a way to store it in a mysql text field so I dont have to mess with the db.

PS: Some asked for full error message here it is:

Warning: Unexpected character in input: '\' (ASCII=92) state=1

PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\x9C\xED}\x8Br\xDB...' for column 'field_text_value' at row 1.

回答1:

Store it as a BLOB. Even if there were a way to store it in a VARCHAR or *TEXT field in a way that survives a round trip, it would be a horrible way.

Are you sure you need compression anyway?

You can also make MYSQL do the compression, e.g. INSERT INTO mytable (compressed_json) VALUE (COMPRESS('[\"the json\"]').



回答2:

Why would you want to add a gzip compressed string into a database? Why don't you just store it as:

mysql_real_escape_string(json_encode($myArray)))