Well, the question is actually a very good one. There is one way to ensure this kind of problems dont happen though.
But first i'd like to clear out the difference between hashing and encrypting
Hashing is when we convert the subject into a long hash. This is very hard to reverse and requires a lot of resources to do it. We usually hash passwords e.t.c.
Encrypting is when we want to store data securely but want to be able to get it back, we convert it into another long thing but we can also reverse it easily(If we know the key)
You can use what is called a 'salt' to protect hashes like your password, since we know that Hash(x) is gonna be VERY different from Hash(x+y), we can use that. Although i wouldnt use MD5 if i were you, it is still great but collisions have been seen in it(A lot of hashing algorithms have them, but being found reduces their security). I recommend you use sha256/sha512. They are very secure and no known collisions have been seen in them so far.
Me being nerdy aside, your problem is very simple. I am going to use the hash function of php in my example.
Since you said the usernames are unique, you can use this for a very safe hashing system
$password = YOUR_PASSWORD_HERE;
$username = USERNAME_OF_USER;
$safe_hash = hash("sha512",$password.$username);
This merges the two username and password and hashes them with the sha512 algorithm(Change the algorithm if you want).
This is very safe as 'password'.'user1' is having a unique and different hash than 'password'.'user2'
If you want to make it even more secure, you can add other stuff like creation times, last names,first names, mobile number, email, creation time, anything that you know and is preferably unique really.
As for encrypting the data(So that you can get it back if you want to) you can use mcrypt.
You can use mcrypt_encrypt and mcrypt_decrypt. You can specify the cipher you want to use and also the mode you want to use. Then when you want your data back, you can again give mcrypt the key, algorithm, mode and the nonsense output that mcrypt_encrypt gave you and you'll have your original data.
I recommend using a very secure key by using hashes, since its very hard to reverse engineer them. Using a sha-256 hash with a good and unique string(I recommend mixing multiple pieces of data in the hash string) will help you secure the data needed.