Escaping User Input
When we create MySQL query strings, we enclose certain values in single quotation marks. If the user input includes single quotation marks, such as with the dance name You'll Always Be Loved By Me, this will cause a silent MySQL error and the action will not be performed, whether it be a search operation or a database insert operation.
The solution is to escape all single quotation marks that are a part of user input, gathered through any form input, whether adding to the database, or searching the database. This can be done easily with a regular expression, but it's not exactly what we might expect, because within the regular expression, the various escapable characters need to be escaped themselves:
# Some user strings may have apostrophe, we need to escape them $easy =~ s/\'/\\\'/g;
So we end up with \\
, an escaped backslash, which equals a backslash, followed by \'
,
an escaped single quotation mark, which equals a single quotation mark. Whew!
Unescaping
It turns out that before we display these strings back to the user, we need to unescape them again. The code to do this is similar but the search and replace terms are swapped:
# unescape them again before showing in user output $easy =~ s/\\\'/\'/g;