php mysql 压缩字符串,php / mysql:如何在文本mysql字段中插入gzcompress-ed字符串?

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.

解决方案

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\"]').

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PHP ,您可以使用以下函数对字符串进行压缩和解压缩: 1. gzcompress() 和 gzuncompress() 函数:使用 gzip 压缩算法对字符串进行压缩和解压缩。 ```php $compressed = gzcompress($string); // 对 $string 进行压缩 $original = gzuncompress($compressed); // 解压缩 $compressed ``` 2. gzencode() 和 gzdecode() 函数:类似于 gzcompress() 和 gzuncompress() 函数,但使用的是 zlib 压缩算法。 ```php $encoded = gzencode($string); // 对 $string 进行压缩 $original = gzdecode($encoded); // 解压缩 $encoded ``` 在 PHP ,您还可以使用以下函数对字符串进行加密和解密: 1. openssl_encrypt() 和 openssl_decrypt() 函数:使用 OpenSSL 库的加密算法对字符串进行加密和解密。 ```php $encrypted = openssl_encrypt($string, "AES-256-CBC", $key, 0, $iv); // 使用 AES-256-CBC 加密算法对 $string 进行加密 $decrypted = openssl_decrypt($encrypted, "AES-256-CBC", $key, 0, $iv); // 解密 $encrypted ``` 其,$key 和 $iv 是加密过程使用的密钥和初始化向量。 2. mcrypt_encrypt() 和 mcrypt_decrypt() 函数:类似于 openssl_encrypt() 和 openssl_decrypt() 函数,但使用的是 mcrypt 库的加密算法。 ```php $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $string, MCRYPT_MODE_CBC, $iv); // 使用 Rijndael-128 加密算法对 $string 进行加密 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $encrypted, MCRYPT_MODE_CBC, $iv); // 解密 $encrypted ``` 其,$key 和 $iv 是加密过程使用的密钥和初始化向量。请注意,mcrypt 库已被弃用,不建议使用。建议使用 OpenSSL 库的加密算法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值