Sending user input into a database and retrieving it – when to escape and how to display

The mysql_real_escape_string() prepares input for database storage:

mysql_real_escape_string() calls MySQL’s library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ‘, ” and \x1a.

mysql_real_escape_string() shouldn’t be used to sanitize HTML, it should only be used on data that you’re about to store in a database. Your sanitization process should look like this:

Input

  1. Accept user input from a form or HTTP request
  2. Create database query using mysql_real_escape_string() in the SQL statement

Output

  1. Fetch data from the database
  2. Run any user-defined data through htmlspecialchars() before printing

Using a database driver such as MySQLi or PDO allows you to use prepared statements, which take care of escaping most inputs for you.

Leave a Reply

Your email address will not be published. Required fields are marked *