How do you serialize and unserialize data?

Discussion in 'PHP' started by Imozeb, Apr 2, 2010.

  1. #1
    I want to store an array in a database. I was told to serialize the data then put it in the database and when I am taking it out I should unserialize the data. How do I do this?

    I've been trying this but it isn't working and I don't know why.

    PHP code:
    
    //get $data from database here
    
    $data = unserialize($data);
    
    //if array not exist then put dummy array
    if(is_array($data) === false){ $data = array('blahblahblah');}
    
    //check if $username is in array if not then put $username in array and return to database so user can't access script again
    if(in_array($data,$username) === false)
    {
    //do some functions
    $data .= $username;
    $data = serialize($data);
    //input into database code here
    }
    
    Code (markup):
    Thanks.

    ~imozeb :)
     
    Imozeb, Apr 2, 2010 IP
  2. organicCyborg

    organicCyborg Peon

    Messages:
    330
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I think your problem may be in trying to store the unserialized data in the variable name that the serialized data is stored in.

    Also, it sounds like the design of your program or data model is a little off if you need to store an array like this in a database. If you modify the structure of your DB, you may be able to find a nicer looking solution.
     
    organicCyborg, Apr 2, 2010 IP
  3. Imozeb

    Imozeb Peon

    Messages:
    666
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Your're right, I modified my DB and now I'm storing data separated by ' , ' so I can easily query the row and use strpos to find my data.

    Thanks!
     
    Imozeb, Apr 3, 2010 IP
  4. Brandon.Add.On

    Brandon.Add.On Peon

    Messages:
    178
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #4
    You could break the array into parts and store each iteration on a separate row. Then you can pull the data from the db and use implode to get it. That way each piece of data will have a unique identifier.
     
    Brandon.Add.On, Apr 3, 2010 IP