When is it necessary to escape double quotes and/or special characters when inserting into a text field in MySQL?
Assuming you have a text field that holds descriptions or articles that have double quotes and/or ampersands, is it necessary to escape them before writing them to the database table?
MySQL (nonstandardly) allows you to use double-quotes as delimiters of string literals:
You would run into trouble if you interpolated content into your SQL string literal, and your content contained double-quotes:
This can be a simple accident, and this probably just causes a syntax error. But attackers can also exploit this cleverly to make your queries do something you didn’t intend.
This could happen if the attacker claims their account name is
Mel" OR "X"="Xand this is called SQL Injection.But if you escape the double-quotes in the content, you can defeat their mischief:
However, it’s simpler to use query parameters, so you ensure that content is separate from SQL code, and can never result in unintended expressions:
Parameters allow you to prepare a query with placeholders, and then provide dynamic content for each placeholder when you execute. For example in PHP with PDO:
See my presentation SQL Injection Myths and Fallacies for lots more information.