mysql序列化后存数组,更新mysql中的序列化数组(不反序列化吗?)

本文讨论了在MySQL中直接更新存储的序列化数组时遇到的问题,特别是当试图替换URL时导致的数据不可用。作者提供了一个解决方案,通过使用特定的字符串替换方法来避免破坏序列化格式。此外,还提到了一个纯SQL的替代方案,但警告这将替换序列化数组内的所有匹配URL,而不仅仅是特定键的URL。
摘要由CSDN通过智能技术生成

Everything I've read says that storing serialised arrays in Mysql is a bad idea - I know that already ;) Unfortunately I'm working with an open source script that uses this method, and changing the structure isn't an option in this scenario.

Is it possible to update this URL without first unserialising?

I originally tried using replace, however it throws an error:

$rssquery = "UPDATE config SET `array` = replace(`array`, \"http://www.oldurl.com\", \"http://www.newurl.com\") WHERE name='config'";

$insert = $db->insert($rssquery);

Could not update UPDATE config SET array = replace('array', 'http://www.oldurl.com', 'http://www.newurl.com') as variable supplied must be an array.

Table name: config

Columns: name | array

Row Needing Updated named: config

Cell Needing Updated named: array

Any other ideas or approaches would be appreciated :) Thanks!

解决方案

If you simply search and replace like that, you will render the serialized data ununsable. Here's what you need to do:

$old = 'http://www.google.com';

$new = 'http://www.someplace.com';

$search = 's:' . strlen($old) .':"' . $old . '"';

$replace = 's:' . strlen($new) .':"' . $new . '"';

$query = "UPDATE config SET array=REPLACE(array, '{$search}', '{$replace}');";

Replace $old and $new with your current and target url's, run the script and execute the generated $query.

Here's a pure SQL solution:

SET @search := 'http://www.original.com';

SET @replace := 'http://www.target.com';

UPDATE config SET array=REPLACE(array, CONCAT('s:', LENGTH(@search), ':"', @search, '"'), CONCAT('s:', LENGTH(@replace), ':"', @replace, '"'));

Note that this will replace EVERY occurrence of the search string in your serialized array. If you are looking to replace a specific key, you have to be more, huh, specific.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值