Unserialize through query at database level itself

后端 未结 8 432
清酒与你
清酒与你 2020-12-02 12:53

I have a column value stored in the database as:

a:2:{i:0;s:2:\"US\";i:1;s:2:\"19\";}

I want to unserialize it during the mysql

相关标签:
8条回答
  • 2020-12-02 13:39

    How about this? This is a MySQL user-defined function with embedded php:

    CREATE FUNCTION unserialize_php RETURNS STRING SONAME 'unserialize_php.so';
    

    Usage example:

    SELECT unserialize_php('O:8:"stdClass":2:{s:1:"a";s:4:"aaaa";s:1:"b";s:4:"bbbb";}', "$obj->a") 
    AS 'unserialized';
    
    +--------------+
    | unserialized |
    +--------------+
    | aaaa         |
    +--------------+
    1 row in set (0.00 sec)
    
    drop function unserialize_php;
    

    Source: https://github.com/junamai2000/mysql_unserialize_php

    You can create a MySQL user-defined function and call zend_eval_string inside of the function so that you can bring back PHP variables to a MySQL result. I implemented a sample program. You can try it.

    0 讨论(0)
  • 2020-12-02 13:40

    From http://www.blastar.biz/2013/11/28/how-to-use-mysql-to-search-in-php-serialized-fields/

    Standard array

    SELECT * FROM table WHERE your_field_here REGEXP '.*;s:[0-9]+:"your_value_here".*'
    

    Associative array

    SELECT * FROM table WHERE your_field_here REGEXP '.*"array_key_here";s [0-9]+:"your_value_here".*'
    
    0 讨论(0)
  • 2020-12-02 13:42

    You can join your table simply in this way

        SELECT 
        table_to_join.ID as table_to_join_ID ,
        serialized_table.ID AS   serialized_table_ID,
    FROM
        table_to_join
            LEFT JOIN
        serialized_table  ON  serialized_table.array_field  REGEXP CONCAT_WS('','.s:[0-9];s:', table_to_join.ID ,';.') ;
    

    Take mention. I use index from 0 to 9 in table. If you have other indexes you must correct regexp

    0 讨论(0)
  • 2020-12-02 13:46

    It's a very bad practice to add programming language dependent structures to database. If you do so, you always have to rely on that language.

    The best approach is to have normalized table structure (different fields or tables).

    The next approach is to save data as a delimited string (e.g.: 0,US,1,19). Then you can use MySQL's SUBSTRING() or to use standard serialization mechanisms like JSON encode.

    0 讨论(0)
  • 2020-12-02 13:47

    For serialized arrays You can use function getPhpSerializedArrayValueByKey from here

    0 讨论(0)
  • 2020-12-02 13:51

    MySQL doesn't know what a PHP serialization is. You can't do it.

    0 讨论(0)
提交回复
热议问题