jacekn
jacekn

Reputation: 1541

What's the best way of escaping quotes in a php script that saves to mysql?

I'm going back and forth with this, so I figured I'll ask here. I'm hoping for a single technique that will work for all input fields (text, select, textarea).

  1. First we process user input using php script. There could be some validation errors so form may need to be redisplayed with user entered values. htmlspecialchars($fieldValue, ENT_QUOTES) doesn't work here because if there is a validation error and form is redisplayed, all quotes entered by user are converted to \". At least in a text area.

  2. Once the form is validated successfully, we need to send input to the database. Column values need to be 'safe' so some conversion is required. I understand I may need to apply some form of conversion when reading from database, as well, although I hope to be wrong on this one.

Looking for a good practice that does not involved too much code.

===

Just as an update. In a Domino form, there is no escaping of any kind and no special processing is required. Notes just does it for it automagically. In a Java application that uses JPA, all of this 'safety' is handled automagically, as well. I understand that php may not have the equivalent but this is such a common issue that I choose to believe I'm missing some very simple solution to this.

Upvotes: 0

Views: 62

Answers (3)

Brent Baisley
Brent Baisley

Reputation: 12721

You can use an ORM like Doctrine to do a lot of stuff automatically. You really should be using PDO for DB access, which will allow you to do "binding" instead of "escaping". Just using escaping can get problematic with UTF8 characters and encoding.

Upvotes: 0

Burhan Khalid
Burhan Khalid

Reputation: 174624

Quick fix for the \" problem, turn magic_quotes off, which you shouldn't be using anyway.

For your other problem, use a driver that supports prepared statements, and if you are looking for a JPA equivalent don't and instead use an ORM.

For validating user input in forms, use a form library which will take care of these mundane tasks.

Upvotes: 0

Frederick Marcoux
Frederick Marcoux

Reputation: 2223

Simply use mysql_real_escape_string() to filter input that needs to go in DB!

Upvotes: 1

Related Questions