Pretty simple, you have a couple options. One simple solution is to have a table with all the possible codes and a field for the username/id/identifier of the person who consumed the code.
For example, [code_id], [user_id]
As such, you can simply query the table for a row with an empty [user_id] to access a new unused code. Additionally, in the table with users (assuming you have one), keep a [referral_code] column with the code that the person was referred by. Subsequently you can aggregate referrals with simple queries thereafter.