Do I need to escape DB input? Do I need to escape DB input? database database

Do I need to escape DB input?


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.


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>.


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.