Nerfair Nerfair - 1 year ago 164
MySQL Question

Save to MySQL serialized info with quotes

Trying to save serialized string to SQL, but then i am having problems with unserializing it because of quotes.

Example, string is "te'st", after serialize we have


But to save it to SQL we need to add slashes, and i am doing


after this, in our MySQL db we have


And this is the problem. s:6 means we have 6 symbols string, but our "te'st" is only 5, so when we trying to unserialize it, we getting error.

How to solve it? Tried htmlspecialchars and mysql_real_escape_string


How i use mysql_real_escape_string

mysql_query("INSERT INTO `table`(`string`) VALUES ('" . serialize(array('iId' =>$aSqlResult['typeID'], 'sName' => mysql_real_escape_string($sScanResultLine))) . "')");

Answer Source

You should pass the data through the escape function after the serialization, not before - which is what you are doing now.

$serialized = mysql_real_escape_string(serialize($data));

Use a parameterised query with PDO or MySQLi and you can forget about the escaping altogether.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download