Why is PDO better for escaping MySQL queries/querystrings than mysql_real_escape_string?

Viewed 37783

I've been told that I'd be better using PDO for MySQL escaping, rather than mysql_real_escape_string.

Maybe I'm having a brain-dead day (or it may be the fact I'm by no stretch of the imagination a natural programmer, and I'm still very much at the newbie stage when it comes to PHP), but having checked out the PHP manual and read the entry on PDO, I'm still no clearer as to what PDO actually is and why it's better than using mysql_real_escape_string. This may be because I've not really got to grips with the complexities of OOP yet (I'm assuming it's something to do with OOP), but other than the fact that variables and array values seem to have a colon infront of them, I'm still not sure what it actually is and how you use it (and why it's better than mysql_real_escape_string. (It also may have something to do with the fact that I don't really have a clear understanding of what 'classes' are, so when I read "PDO class" I'm none the wiser really).

Having read an article or two on the 'Developer Zone' bit of the MySQL website, I'm still no clearer. As I can't even figure out what it is at the moment, I think probably using it is a bit beyond me right now, but I'm still interested in broadening my education and finding out how I could improve things.

Could anyone explain to me in 'plain English' what PDO is (or point me in the direction of something on the subject written in plain English), and how you'd go about using it?

6 Answers

Why is PDO better for escaping MySQL queries/querystrings than mysql_real_escape_string?

Simply because "escaping" alone makes no sense.
Moreover, it's different incomparable matters.

The only problem with escaping is that everyone takes it wrong, assuming it as some sort of "protection".
Everyone says "I escaped my variables" with the meaning "I protected my query".
While escaping alone has nothing to do with protection at all.

Protection can be roughly achieved in case of I escaped and quoted my data, but it is not applicable everywhere, for the identifiers for example (As well as PDO, by the way).

So, the answer is:

  • PDO, when doing escaping for the binded values, applies not only escaping but also quoting - that's why it's better.
  • "escaping" is not a synonym for the "protection". "escaping + quoting" roughly is.
  • but for some query parts both methods inapplicable.
Related