phpmysqlarrays

mysql select query within a serialized array


I'm storing a list of items in a serialized array within a field in my database (I'm using PHP/MySQL).

I want to have a query that will select all the records that contain a specific one of these items that is in the array.

Something like this:

select * from table WHERE (an item in my array) = '$n'

Solution

  • So you mean to use MySQL to search in a PHP array that has been serialized with the serialize command and stored in a database field? My first reaction would be: OMG. My second reaction would be: why? The sensible thing to do is either:

    1. Retrieve the array into PHP, unserialize it and search in it
    2. Forget about storing the data in MySQL as serialized and store it as a regular table and index it for fast search

    I would choose the second option, but I don't know your context.

    Of course, if you'd really want to, you could try something with SUBSTRING or another MySQL function and try to manipulate the field, but I don't see why you'd want to. It's cumbersome, and it would be an unnecessary ugly hack. On the other hand, it's a puzzle, and people here tend to like puzzles, so if you really want to then post the contents of your field and we can give it a shot.