This is MySQL's Bad Idea #573 (after #384, which I've blogged about before) I've just had a terrible experience with a bug report from the jOOQ User Group, related to escaping of backslashes in string literals in MySQL. First, I thought to myself, whatever. SQL doesn't escape backslashes. The only escape character within a string … Continue reading MySQL Bad Idea #573 →
We're all being drilled over and over again to always use mysqli::escape_string, PDO::quote, or preferably prepared statements when escaping user-supplied strings for use in MySQL queries.
The downside to these methods is that they only work when there's an open connection to a server. So what if there's no connection available? In traditional Unix philosophy I'm writing an export script that doesn't execute SQL statements right to a server, but sends them to stdout. Forcing people to make a connection seems like a major inconvenience.
So what's left? Manual escaping I suppose.. The manual page for mysqli::escape_string mentions: Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", …
[Read more]Two examples of escaping data are the following:
- Before you insert a value into a SQL query, using for example mysqli::real_escape_string() or PDO::quote().
- Before you insert data into your output HTML, using htmlspecialchars().
The question I'd like to ask today is, when to do this? There are two possible moments:
- Right when the data comes in. For SQL this used to be done with 'magic quotes' quite a bit in PHP-land. In general I don't see this happening a lot anymore for SQL. I do however see data encoded using htmlentities/htmlspecialchars before entering the database.
- The other way to go about it, is to only escape …