Yes. Always. Or, better yet use placeholders (which are available in both PDO and mysqli) see best way to stop SQL injection in PHP.
The reason to always use some form of escaping (even the outdated and cumbersome mysql_real_escape_string
) is to be consistent. Saving the few cycles because "it isn't needed here" (and it "isn't needed here" because sha1
returns a string of hex characters) is irrelevant if it -- due to lack of consistency -- leads to bugs and/or compromises later.
Bugs/compromises can be introduced by a lack of consistency and forgetting to "escape" a different field later or it may be due to a small code range where the new requirements to "escape" was overlooked. (Imagine if a future version saves a binary or base-64 SHA1 signature.) Both of these trivial vectors can be eliminated through better practices.
Happy coding.
The user enters data. The database stores the data. The point of "escaping" the data (or, better yet, use placeholders/parameterized queries) is making sure the data makes it into the database correctly and safely. If the data needs to be treated specially, then handle this at the data level -- the actual operation of dealing with the SQL should be simple, consistent, and reliable. (Note that mysql_real_escape_string
doesn't change the data seen by the database, rather it ensures that the data is the real data -- that which was passed to the mysql_real_escape_string
function -- after the database parses the SQL command.)
It is quite sad, but the entire point of needing to "escape" still exists because of the incorrect concatenation of data into SQL strings. This "problem" has been solved for many, many years with the use of placeholders which allows the SQL command and the data to be kept isolated. Prepared statements may also be more efficient, depending upon other factors. And, quite honestly, I can't see how people can stand to look at/write the mess created with string manipulation (even without all the added "escaping" code) of SQL commands in general.