I am using a template system and I have been pondering what the addslashes() function can do for me and if/when I should use it when inserting stuff into the database.
I know what it does, but I just dont know how I should be using it properly.
Maybe I should stripslashes to clean it up before going in the database and when its being output, use htmlspecialchars and addslashes. The thing is, I still get puzzled when its not exactly needed for an echo.
Are you sure you have to stripslashes when retrieving the data from the database?
For example, when inserting a quote ' addslashes converts that to \' and inserts into the mySQL database, which inteprets both those characters as a single quote. So, I think there is no need to stripslashes...
SELECT * from article WHERE body LIKE '%$search_term%' ORDER BY article_id
Where, $search_term is entered by the user through a form. If $search_term is something simple like Banner Management, the SQL Query becomes:
SELECT * from article WHERE body LIKE '%Banner Management%' ORDER BY article_id
and everything would work fine.
But, just incase $search_term is something like Matt's Script Archive the SQL Query would become:
SELECT * from article WHERE body LIKE '%Matt's Script Archive%' ORDER BY article_id
Notice 3 single quotes in that query! It would produce an error parsing the query.
Instead, if you use the builtin PHP function addslashes:
$SQL = "SELECT * from article WHERE body LIKE '%" . addslashes($search_term) . "%' ORDER BY article_id"
the single quote (and other special chars in $search_term) gets escaped, and the SQL query becomes:
$SQL = "SELECT * from article WHERE body LIKE '%Matt\'s Script Archive%' ORDER BY article_id"
and everything works as expected.
the \' tells the SQL parser to intepret it as a single quote, to be stored in the database.
NOTE: PHP can be configured to automatically add these slashes to all FORM (GET/POST) and cookie INPUT from the user (thats what gpc_magic_quotes() is for). So, this would eliminate the need of using addslashes. However, I prefer to explicitly addslashes() and turn off auto slashing.
The stripslashes is used to remove slashes. This is normally only used if you want to remove slashes from user INPUT that were added automatically by PHP (gpc_magic_quotes() function).
Bookmarks