Php Serialize data in Mysql

I tested your example on my system, and after serialization, the following value is returned:

string(42) "a:1:{i:0;s:24:"a:4:{i:1;s:7:"fdsfdsf";i";}"

This is what will be added to the database. But, storing user input plain in database is highly discouraged. You should first format the plain user input with mysql_real_escape_string() as it will escape critical characters.

Apart from that, if unserialize() is called on the serialized text read back from database, the array is properly returned. It should be safe, but can produce unexpected results.

Be extremely careful with storing serialized arrays in a database. Serialization returns a string, so the field you store the data in is usually VARCHAR or TEXT. If you simply overwrite the stored array with a new one, the old data will be completely lost. To update the database, make sure you first read the data from the database into an array, and update it, and only then write it back to the database.

While it is not forbidden, using and storing stuff serialized in database usually creates a lot of issues. The database has a lot of datatypes known by default, and big serialized arrays create overhead and complicates execution, and is just simply a pain in the ass if the system later needs to be modified. And you cannot use relation queries on serialized fields.


The old way

When you're still using mysql_ you could write queries like this:

$sql = sprintf("INSERT INTO mytable (a) VALUES ('%s')",
    mysql_real_escape_string(serialize($myvar))
);
mysql_query($sql) or die("oh no!");

The recommended way

For PDO and mysqli you get the option to use prepared statements, which comes highly recommended for exactly the purpose of preventing SQL injection attack vectors. An example in PDO:

$stmt = $db->prepare('INSERT INTO mytable (a) VALUES (:myvar)');
$stmt->execute(array(
    ':myvar' => serialize($myvar),
));

Field lengths

Also, make sure the length of your serialized data doesn't exceed the column size of the table field; a truncated serialized variable is pretty much useless.