Question

One of the former developers in an old system I'm working on used PHP serialize() to flatten one array of data into one column of a MySQL table.

I need to write a complex query that involves this column. Is there a way to unserialize the data (even if it's into a comma separated string) within the SQL query or do I need to pass the results back to PHP?

Was it helpful?

Solution

Serialized PHP data is just a string, so for "simple" searches, you can use basic MySQL string operations.

e.g. The serialized array has a name parameter and you need to match against that, so

... WHERE LOCATE(CONCAT('s:', LENGTH('foo'), ':foo') ,serializeddatafield) > 0

which would produce

WHERE LOCATE('s:3:foo', serializeddata) > 0

But then, this would find ANY strings whose value is foo anywhere in the data, and not necessarily in the particular array field you want.

e.g. you're probably better off yanking out the whole field, deserializing in PHP, and then doing the search there. You could use the above technique to minimize the total number of strings you'd have to yank/parse, however.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top