Is there any way for deserialize and serialize data in mysql without using php and just using SQL language?
working on woocommerce plugin that stores cart items as serialized in database.
The goal is to make a query to cart table and fetch cart items and then send the result to an API.
cart items are stored as serialized data in table that is like :
a:1:{s:4:"cart";a:2:{s:32:"76dc611d6ebaafc66cc0879c71b5db5c";a:11:{s:3:"key";s:32:"76dc611d6ebaafc66cc0879c71b5db5c";s:10:"product_id";i:128;s:12:"variation_id";i:0;s:9:"variation";a:0:{}s:8:"quantity";i:1;s:9:"data_hash";s:32:"b5c1d5ca8bae6d4896cf1807cdf763f0";s:13:"line_tax_data";a:2:{s:8:"subtotal";a:0:{}s:5:"total";a:0:{}}s:13:"line_subtotal";d:500;s:17:"line_subtotal_tax";i:0;s:10:"line_total";d:500;s:8:"line_tax";i:0;}s:32:"65ded5353c5ee48d0b7d48c591b8f430";a:6:{s:3:"key";s:32:"65ded5353c5ee48d0b7d48c591b8f430";s:10:"product_id";i:132;s:12:"variation_id";i:0;s:9:"variation";a:0:{}s:8:"quantity";i:1;s:9:"data_hash";s:32:"b5c1d5ca8bae6d4896cf1807cdf763f0";}}}
and after deserializing it in online tools I get this stucture:
Array
(
[cart] => Array
(
[76dc611d6ebaafc66cc0879c71b5db5c] => Array
(
[key] => 76dc611d6ebaafc66cc0879c71b5db5c
[product_id] => 128
[variation_id] => 0
[variation] => Array
(
)
[quantity] => 1
[data_hash] => b5c1d5ca8bae6d4896cf1807cdf763f0
[line_tax_data] => Array
(
[subtotal] => Array
(
)
[total] => Array
(
)
)
[line_subtotal] => 500
[line_subtotal_tax] => 0
[line_total] => 500
[line_tax] => 0
)
[65ded5353c5ee48d0b7d48c591b8f430] => Array
(
[key] => 65ded5353c5ee48d0b7d48c591b8f430
[product_id] => 132
[variation_id] => 0
[variation] => Array
(
)
[quantity] => 1
[data_hash] => b5c1d5ca8bae6d4896cf1807cdf763f0
)
)
)
each of this object properites is needed to be accessed and store in a columns and then sending the result of query to an API.
How could deserialize these data in SQL language?
2
Answers
serialize
PHP function serializes a data structure into a string representation that’s unique to PHP and can be reversed into a PHP object using unserialize.MySQL doesn’t know what a PHP serialization is. You can’t do it using just SQL.
I have been struggling with a similar issue: Deserialising and serialising data from table wp_postmeta, to do search-and-replace on certain parts of it (I’m translating WooCommerce-sites and I would prefer to do it all within MySQL, rather than using PHP). In my case, the search-and-replace always happened on the fourth s-element. I developed a sproc for this. It probably doesn’t suit your exact use case, but maybe it’s close enough for adapting it to your needs: