6

I read that with PDO you don't need to escape variables if you use prepare and pass the variables in execute:

$st = $dbh->prepare("INSERT INTO mytable (name,email) VALUES (?,?)");
$st->execute(array($_POST['name'], $_POST['email']));

Is this tru?

Or do I still need to do something with $_POST there?

3
  • 1
    Despite not needing escaping, be sure to check the input values for sanity, acceptable ranges, properly formatted email, etc, and return error messages to your user where appropriate. Commented Dec 5, 2011 at 15:02
  • yes, I was just curious about sql attacks Commented Dec 5, 2011 at 15:10
  • As long as you're strict about what you place into your query and where you do it (i.e. use parameters at all times, never ever ever allow user-supplied data to leak into concatenated parts of dynamic queries) then you'll be safe. Commented Dec 5, 2011 at 15:20

3 Answers 3

5

On prepared statements, no escaping is necessary (and escaping things yourself will result in double-escaping, causing escaped data to be written to the DB).

However, PDO prepared statements CANNOT handle all query variants, and sometimes you'll have to insert "foreign" data directly into a query string, which means you'll be responsible for escaping it properly. In particular, dynamic queries where the table and/or field names change cannot be specified using prepared statements. e.g.

SELECT ? FROM ? WHERE ?=?

cannot be done. Only values can specified with placeholders.

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly. fields and table names cannot be specified with placeholders.
2

Short answer: No, you don't need to escape anything. Parameterized queries are totally freakin' awesome! :)

Long answer: No, you don't need to escape anything as it's going into the database. However, you should still use htmlspecialchars when displaying the database output from queries to prevent XSS attacks, otherwise you'll end up with someone stuffing something like this in an arbitrary field:

<script type="text/javascript">alert('sup, I'm in ur site!');</script>.

1 Comment

Stressing the when displaying the database output. You should in general not store HTML in the database unless your field truly is HTML.
2

This is true; the code is correct (although you may want to handle the case that $_POST['name'] is not set).

PDO's prepared statement functionality hands over the values in a format that does not need explicit escaping.

1 Comment

It's somewhat important to note that PDO doesn't actually do any escaping, it just isolates the data from query language entirely.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.