views:

438

answers:

3

I'm trying to store a complex object here and am doing that by serialising the object running a mysql_real_escape_string on it and inserting it into a mysql database.

However when I retrieve it running a sql query - I'm using Zend frameworks Zend_DB_Table here but anyway - and when I try to stripslashes and unserialize I dont get my object back. I've tried to just unserialize without stripping slashes and all but nothings working. Help please. :(


UPDATE

This is weird. I made a simple page which just unserializes a serialised object. If I take the serialized string as it is retrieved from the database and unserialize it via this other page which just has an unserialize() on it - it works perfectly and I get my object back. However in the code where ironically I'm retriving the string and I run the exact same unserialize option there :( Its not working!

So basically there is nothing wrong with the serialized string - for some weird reason it won't unserialize it in my application but it unserializes somewhere else :-S it makes no sense!

+2  A: 

You shouldn't run stripslashes on it - the database will give you back the right string to put into unserialize.

Make sure you have notices turned on and echo the string before you unserialize it - does it look right?

Greg
How do I turn notices ON? Well I've tried to stripslash and unserialize as well as unserialize without stripping slashes and it still doesn't work :(
Ali
error_reporting(E_NOTICE);This will enable notices, but also override your current error reporting levels.http://uk.php.net/manual/en/book.errorfunc.php for more info
Neil Aitken
+6  A: 

You probably need to run it through base64 encoding first:

$safe_string_to_store = base64_encode(serialize($data));

Then to get it back out:

$date = unserialize(base64_decode($safe_string_to_store));

Try that and let us know if it works.

(and dont run stripslashes on it - there is no need to)

ae
WOW! Tried that and it worked like a charm! I have no idea why it wasn't working before but thanks man - its working fine now.
Ali
+1  A: 

You should be able to just do the following:

Assuming MyTable is your instance of Zend_Db_Table_Abstract:

$t = new MyTable();
$n = $t->createRow();
$n->serializedfield = serialize($data);
$n->save();

and let Zend DB take care of the escaping for you.

If you're doing it via an insert(), you shouldnt need to do anything either (the above uses insert())

Otherwise use $db->quoteInto() like

$db->quoteInto('INSERT INTO mytable (serializedfield) values (?)', serialize($data));
Justin