If you are using the regular MySQL driver module for PHP, then yes, mysql_real_escape_string()
is the way to go. You can ignore addslashes()
and stripslashes()
entirely, in fact.
Your query creation will look something like this:
$sql = "INSERT INTO tbl (x) VALUES '".mysql_real_escape_string($x)."'";
mysql_real_escape_string()
should be used on any user input that is going into your query. Note that you don't want to escape your data any other way before inserting it. You shouldn't use addslashes()
or htmlentities()
, which are common mistakes when storing HTML fragments in a database. You should not need to unescape your data in any way after you have retrieved it.
As other posters mention, there are other MySQL database driver modules for PHP, including PDO and MySQLi. Both offer a feature known as prepared statements, which is an alternative method of creating queries that handles escaping for you.