tl/dr: The ability to properly escape user input once does not mean
your company will do it every time. You can't. Don't even try.
You have 2 good answers for the specific question you asked. However, I wanted to touch on some broader issues that are very important here:
Prepared statements aren't a foolproof solution to SQLi
Prepared statements are a strong safeguard to SQLi, but they aren't the solution to SQLi because prepared statements can't solve all SQLi issues. You can't user prepared statements when the table name or column name comes from user input, nor can you use them to specify pagination parameters on the query. As a result, they are a key security measure, but you can still have SQLi vulnerabilities when using prepared statements.
Not using prepared statements guarantees SQLi vulnerabilities!
While it is certainly possible to use proper escaping methods to properly escape and build a single query, like in your example, this is not a successful long-term strategy. I know, because I've been personally involved in cleaning up breaches that happened because, years ago, a team decided, "We don't need prepared statements, we'll just use escaping!" That works fine as long as you can guarantee that every single developer who ever writes a query with user input understands perfectly how to escape user input in every injection point. This will never happen. Can you spot the SQLi vulnerability in this simple example?:
$result = mysql_query("SELECT * FROM users WHERE id=" . escapeSimple($_POST['user_id']))
The ability to properly escape user input once does not mean your company will do it every time. You can't. Don't even try.
Other Gotchas
Some more points:
md5
for passwords died 15 years ago. PHP has password_hash. Use it.
- Never directly compare two hashes. This introduces potential side-channel attacks. Use password_verify.
- The
mysql_query
line of functions were deprecated a long time ago. Switch to mysqli or PDO
- Why are you explicitly checking if the username matches when you already did that in the query? Just exit if the query returned no results.
escapeSimple
do?