I have the following code:
<?
$string="< input type=button value='Open' onclick='document.location.href=\"".format_URL("phpfolder",$sesion)."objects/construct.php?id_object=$id_object\"' >";
mysql_query( "insert into db (code) values ('$string')" );
?>
When escaping with $string=mysql_real_escape_string($string);
the result is
$string=\"< input type=button value=\'Open\' onclick=\'document.location.href=\"\".format_URL(\"phpfolder\",$sesion).\"objects/construct.php?id_object=$id_object\"\' >\";
And it should be like this:
$string=\"< input type=button value=\'Open\' onclick=\'document.location.href=\\\"\".format_URL(\"phpfolder\",$sesion).\"objects/construct.php?id_object=$id_object\\\"\' >\";
Why mysql_real_escape_string() don't recognize that it has to escape the first backslash of \""
to convert it to \\\"\"
?
Is this a bug in PHP ?
I've tried to apply the functions like addslashes, html_entities, str_replace, preg_replace, etc. Nothing works as expected or I'm using it wrong.
What's the way to do it?
Simply dont use mysql_* functions. Just use prepared statements and you will NOT have this problem. Here is an example in PDO:
$stmt = $pdoObject->prepare('INSERT INTO MyTable (code) VALUES (:code)');
$stmt->bindParam(':code', $string, PDO::PARAM_STR);
if ($stmt->execute()) {
echo 'Success';
} else {
echo 'Failure';
}
As simple as that. Much cleaner & safer code.
Now the main problem is you saving entire html/js into table. Your table will grow huge very fast in terms of size. Why dont you just save essential ID's or attributes into the table & build that html by retrieving it from the table.
You should only be saving $session
& $id_object
into your table. With those two variables you can build the html after.