Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php Serialize data in Mysql

I save data in my DB (mysql) with "serialize($array);". This data came from a form with an input field. I want to know what happen if i insert something like "a:4:{i:1;s:7:"fdsfdsf";i" in the form field. could break my data stored in the DB? Thanks!!

like image 577
alejoabella Avatar asked May 31 '12 15:05

alejoabella


1 Answers

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.

like image 86
Whisperity Avatar answered Sep 29 '22 08:09

Whisperity