MySQL PHP Escape String '\' - Why is it not saved in the database with the backslash?
Let me begin by saying that you should really not really store data in any particular escaped format in the database, you'll regret it later if you need to extract it in another format or search the data for some reason later. The format you're saving now looks good, and adding backslashes for Javascript is better done in code when passing the data to the actual Javascript.
Now this is why it currently behaves like it does;
In the string 'Tom\'s things'
, \'
is a character escape sequence and is really only used to let MySQL understand how to parse the SQL string, it's never saved as is to the database.
The reason you escape the character '
in the SQL statement you're showing to begin with is that otherwise MySQL has no way of knowing that the string does not end at the single quote after 'Tom
.
If you use MySQLi or PDO prepared statements instead of building your SQL statements yourself, MySQL will let you save values entirely unchanged without having to ever escape anything. This is definitely the preferred option, since the MySQL API that does not support prepared statements is deprecated anyway.
The backslash is treated as an "escape character". If there was no backslash your string would end at Tom
but the remaining s things
would cause a syntax error.
The \
tells MySQL to not treat the escaped '
as a string delimiter but carry on until the next unescaped '
is found.
This escape character is only used for the query purposes and is not treated as part of the string you want to update.
Like Alvin suggested in comments, if you want to keep the backslash in your database you have to add it by adding another escaped backslash, i.e. \\
. This would make your query look like:
UPDATE `TABLE` SET `PERSONAL_BELONGINGS` = 'Tom\\\'s things'
And the data in database would look like:
|Tom\'s things|
You can read more about string literals and escaping special characters in MySQL Manual
It's worth noting though, that storing an already escaped string in database is a bad practice. You should take care of escaping special characters in your code.