Search code examples
phpmysqlmysql-real-escape-stringstripslashes

Confusion about mysql_real_escape_string and strip_slashes


I have users entering their name, as in: O'riley.

Before I enter this data into the MySQL DB, I run mysql_real_escape_string.

Problem is, when I then select this data for display and use later, it comes out as: O\'riley.

Obviously, this is the intended operation. What I'm wondering is if there's someway to be sure I can store it in the DB (still safely escaping possible malicious code), so that I don't have to use strip_slashes() on the output EVERY time I call the data throughout the entire web app? Or, am I missing something here?

Thanks.

UPDATE Please refer to the comments in Deceze's answer.


Solution

  • Thank you everyone for the answers. I will award the +50 out, but I wanted to tell my real solution here, all which people did help with...

    I was performing mysql_real_escape_string on all of the data AS SOON as it posted (before any processing). So, a slash was added to escape the ' character that was submitted. This, we know is normal.

    However, there was no reason that the backslash \ should show up in the DB entry, right? The escape was there to be sure the ' was entered.

    Turns out, AFTER escaping, I would then save the variable to be reloaded to the page in the session, in case the user had an error that PHP found while validating all of the form fields. In this case, the user's input (formerly O'riley was now printed to their screen as O\'riley. Then, the user didn't catch this - so they would often just fix their error that PHP caught during validation (unrelated to the name field), and thus the O\'riley would land in the database because mysql_real_escape_string would escape the characters.

    Lesson: When processing a form, FIRST save data for form-refill use. SECOND validate form fields. THIRD escape the data for processing into the database.

    Or better yet, use PDO and avoid this =).

    Comments welcome. THANKS ALL!