Actually, I would argue that what Weedpacket suggested makes more sense: there is no need to calculate a hash if the passwords do not even match, so one should check first, then hash if they match. Not only that, but using trim() and mysql_real_escape_string on a hexadecimal numeric string as produced by sha1() is pointless. We do not even know if mysql_real_escape_string() is the correct function since the database API used is not known.
Note I used sha1(). It's more reliable and better encryption than md5().
It is not encryption, it is a cryptographic hash. Whether it is better than MD5 for such password hashing is disputed by the folks at phpBB, but either way a hash alone is just not enough. At the very least one should include a salt for each user.