Using addslashes to escape data going into the datatabase

Posted in Articles

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

You can not just take whatever user inputs and insert it into the database directly. Because what if the user data contains a single quote as in “The Jetson’s”.   That string with single quote when concatenated with a SQL insert statement can alter the SQL statement and not do what you intended.

Malicious users can specifically construct certain strings to run certain SQL commands on your database.  This is known as a SQL injection attack.

So in order to get strings with quotes into the database, those special characters must be “escaped” by adding a backslash in front of these characters.   The addslashes() function can be used to add such slashes.  If you have magic quotes turned on, magic quotes will add the slashes automatically.  In any case, magic quotes is now deprecated and discouraged.  You don’t want to have slashes added twice, so you may have to use get_magic_quotes_gpc() to determine if it is turned on or not.

Instead of addslashes, it may be better to use DBMS specific escape function.  For MySQL database, it is the mysqli_real_escape_string()