Sometimes you need to store things like file paths into a database table during your PHP script’s execution. However, on going back to the database after running your script, you might come across your path with all of its backslashes () missing!

So just what is going on here?

In most cases you will be using a string construct to send your SQL command, in other words, mysql_query() will be sending along a string SQL statement to be processed by the database. However, recall that backslashes usually need to be escaped in order to display a backslash, and in PHP for example, escaping characters is done by using a backslash – so in other words to display a backslash in a string, you actually need to put down two of the things: \

However, when pushing your escaped string through to the database, remember that mySQL also needs to escape the backslashes it receives via your SQL statement, meaning that in actual fact you need to be double escaping your escaped backslashes!

To make this simpler to understand, you want to use this in your SQL string: \\. So what happens now is that the PHP script escapes the above to \ which is then passed along to mySQL which then further escapes it to , leaving you with a nice shiny backslash in your record as a result.

Got it?

Anyway, naturally PHP makes things a little easier for us by providing the handy mysql_real_escape_string() function which will handle the escaping of all special characters for use in a SQL statement, even taking into account the current character set of the connection specified!

Now you know.

Related Link: http://www.php.net/manual/en/function.mysql-real-escape-string.php