我在数据库中保存数据时是否真的需要使用mysql_real_escape_string?

I am using mysql_real_escape_string to save content in my mySQL database. The content I save is HTML through a form. I delete and re-upload the PHP file that writes in DB when I need it.

To display correctly my HTML input I use stripslashes()

In other case, when I insert it without mysql_real_escape_string, I do not use stripslashes() on the output.

What is your opinion? Does stripslashes affect performance badly ?

Do not use stripslashes(). It is utterly useless in terms of security, and there's no added benefit. This practice came from the dark ages of "magic quotes", a thing of the past that has been eliminated in the next PHP version.

Instead, only filter input:

  • string: mysql_real_escape_string($data)
  • integers: (int)$data
  • floats: (float)$data
  • boolean: isset($data) && $data

The output is a different matter. If you are storing HTML, you need to filter HTML against javascript.

Edit: If you have to do stripslashes() for the output to look correctly, than most probably you have magic quotes turned on. Some CMS even made the grave mistake to do their own magic quotes (eg: Wordpress). Always filter as I advised above, turn off magic quotes, and you should be fine.

Do not think about performance, think about security. Use mysql_real_escape_string everytime you're inserting data into DB

It is always best to scrub your data for potential malicious or overlooked special characters which might throw errors or corrupt your database.

Per PHP docs, it even says "If this function is not used to escape data, the query is vulnerable to SQL Injection Attacks."

No, don't escape it. Use prepared statements instead. Store your data in its raw format, and process it as necessary for display - for example, use a suitable method to prevent Javascript from executing when displaying user supplied HTML.

See Bill Karwin's Sql Injection Myths and Fallacies talk and slides for more information on this subject.

See HTML Purifier and htmlspecialchars for a couple of approaches to filter your HTML for output.

Check out a database abstraction library that does all this and more for you automatically, such as ADOdb at http://adodb.sourceforge.net/

It addresses a lot of the concerns others have brought up such as security / parameterization. I doubt any performance saved is worth the developer hassle to do all this manually every query, or the security practices sacrificed.